dsbqfrr098575666 2016-07-05 15:02
浏览 343
已采纳

Javascript - 无法解析通过PHP发送的JSON或字符串

How do i get the json data in Javascript?

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

$result=curl_exec ($ch); // it has json data 

curl_close ($ch);

/* PHP unit test - shows the data is available and it works 
$obj = json_decode($result, true);
foreach($obj as $k=>$v) {
  echo $k . ' ' . $v  . '<br/>';
}
*/

/* But, from PHP i need to send the data to Browser on Ajax/GET request*/
$obj = json_decode($result, true);
echo $obj;
//if i do not use json_decode and only do echo $result; then still
//javascript is unable to parse the json 

So when Javascript is calling that PHP method, its failing to decode as readable format:

$.get(submit_url + '/login?', {
  code_please: '007',
}, function(data_please) {

  // ------------------------------FAIL to READ 
  alert(data_please);
  alert(data_please[0]);
  alert(data_please.id);
  //var duce = jQuery.parseJSON(data_please);
  //var art1 = duce.email;
  //for(oooi in data_please.db) { data_please.db[oooi].id++ } 

});

Output: Array

  • 写回答

2条回答 默认 最新

  • dongxia19772008 2016-07-05 15:04
    关注

    If your getting a JSON encoded string from the curl response you don't need to call json_decode on it, just echo the string out. json_decode will convert it into a PHP array which is not what you want.

    Also you should call your own endpoint using $.getJSON as this will convert the JSON into an object you can use with javascript automatically.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 如何批量获取json的url
  • ¥15 对法兰连接元件所承受的表面载荷等效转化为法兰开孔接触面上的等效表面载荷?
  • ¥15 comsol仿真压阻传感器
  • ¥15 Python线性规划函数optimize.linprog求解为整数
  • ¥15 llama3中文版微调
  • ¥15 pg数据库导入数据序列重复
  • ¥15 三分类机器学习模型可视化分析
  • ¥15 本地测试网站127.0.0.1 已拒绝连接,如何解决?(标签-ubuntu)
  • ¥50 Qt在release捕获异常并跟踪堆栈(有Demo,跑一下环境再回答)
  • ¥30 python,LLM 文本提炼