【问题标题】:undefined value from ajax success response using json data来自使用 json 数据的 ajax 成功响应的未定义值
【发布时间】:2020-07-16 09:26:46
【问题描述】:

我的 CURL 代码如下:

$ch = curl_init("http://my ip address/api/FeedbackCustomerDetails?accessKey=$access_key&AccountNo=$subscriber_code");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);                                                                                                                  
$result = curl_exec($ch);
$response = print stripslashes(json_encode($result));

我的curl的回复如下:

"{"CENTER":"BRADFORD","STATUS":"0","SUB_NAME":"PETER ","ACCOUNT_NO":"HB92008117","ASSOCIATE_ID":"850N027","STATUS_TEXT":"SUCCESS","REGION":"UK"}"

没有 strip_slashes 的输出是:

"{\"CENTER\":\"BRADFORD\",\"STATUS\":\"0\",\"SUB_NAME\":\"PETER \",\"ACCOUNT_NO\":\"HB92008117\",\"ASSOCIATE_ID\":\"850N027\",\"STATUS_TEXT\":\"SUCCESS\",\"REGION\":\"UK\"}"

我尝试了以下并总是得到“未定义”

    success: function(response) {
        alert(response.ACCOUNT_NO);
},

我需要在 span id 中显示数据。我也尝试了以下方法:

$("#subscriber code").text(response[0].ACCOUNT_NO);

response.ACCOUNT_NO;总是导致UNDEFINED

我做错了什么??请求帮助..

【问题讨论】:

  • 在带斜线后可能会丢失 JSON 完整性,所以尝试json_decode() 然后json_encode()
  • 好的,我试过了:$response = json_decode($result, true); $response = 打印 json_encode($response);
  • 但是警报(response.ACCOUNT_NO);未定义。

标签: php json curl


【解决方案1】:

你有没有试过先 JSON.parse() 结果? 您有此属性的“未定义”值,因为您的响应是字符串,而不是对象。并且字符串没有名为“ACCOUNT_NO”的属性。 您应该首先将您的响应解析为对象。

response = JSON.parse(response);
alert( response.ACCOUNT_NO );

【讨论】:

  • 谢谢。在@jidexl21 和 JSON.parse 推荐的 json_decode() 和 json_encode() 之后,它工作正常。
  • 如果你不想一直JSON.parse你的回复,在发送输出之前使用header("Content-type:application/json");
猜你喜欢
  • 2015-05-13
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2023-02-21
相关资源
最近更新 更多