简体   繁体   English

JSON.parse() 不会将我的 PHP 字符串转换为 JavaScript 对象

[英]JSON.parse() is not converting my PHP string to a JavaScript object

I have used json_encode() to echo an associative array from PHP to JavaScript through this $.post method:我使用json_encode()通过这个 $.post 方法将关联数组从 PHP 回显到 JavaScript:

$.post("php/myfile.php", {}, function(data){
    exercises = data;
    //exercises = json.parse(data);   // console -> Uncaught ReferenceError: json is not defined
    alert(typeof exercises);          // alerts -> String
    alert(exercises);                 // alerts -> {"1":"Bench Press","2":"Squat","3":"Deadlift"}
    alert(json.stringify(exercises)); // console -> Uncaught ReferenceError: json is not defined
});

For some reason I can't convert the string to a JavaScript associative array using json.parse() .出于某种原因,我无法使用json.parse()将字符串转换为 JavaScript 关联数组。

What's my issue?我的问题是什么?

You can pass json as the dataType to the ajax call so that jQuery will pass the converted value您可以将json作为 dataType 传递给 ajax 调用,以便 jQuery 将传递转换后的值

$.post("php/myfile.php", {}, function (exercises) {
    alert(typeof exercises); // alerts -> String
    alert(exercises);
}, 'json');

In your code the problem is the case of json , it should be JSON.parse() not json.parse()在您的代码中,问题是json的情况,它应该是JSON.parse()而不是json.parse()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM