Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JSON.parse:从PHP JSON_encode接收assoc数组时出现意外字符_Php_Jquery_Ajax_Json_Post - Fatal编程技术网

JSON.parse:从PHP JSON_encode接收assoc数组时出现意外字符

JSON.parse:从PHP JSON_encode接收assoc数组时出现意外字符,php,jquery,ajax,json,post,Php,Jquery,Ajax,Json,Post,更新 因此JQuery.post()函数接收有效的JSON。我知道函数调用中的属性“json”应该已经足够获取原始数组,因此不需要.parseJSON()。我想这就是为什么我在使用这个函数时会出现语法错误 但不知怎的,如果没有.parseJSON(),我仍然无法访问数组。事实上,当我使用typeof(data)时,它仍然是一个字符串。我可以将它写入控制台,它仍然是有效的JSON 如何将我的数组(最初通过json_encode()编码一次的关联PHP数组)用作JavaScript中的普通关联数组

更新

因此JQuery.post()函数接收有效的JSON。我知道函数调用中的属性“json”应该已经足够获取原始数组,因此不需要.parseJSON()。我想这就是为什么我在使用这个函数时会出现语法错误

但不知怎的,如果没有.parseJSON(),我仍然无法访问数组。事实上,当我使用typeof(data)时,它仍然是一个字符串。我可以将它写入控制台,它仍然是有效的JSON

如何将我的数组(最初通过json_encode()编码一次的关联PHP数组)用作JavaScript中的普通关联数组

原创帖子

我已经收到这个语法错误好几天了,它快把我逼疯了。我读了很多帖子,我知道我错过了一件非常简单的事情。请帮忙。提前谢谢

var institute = $.post("../libraries/load_content.php",
    {
        funct:   "getInstituteAddress",
        ins_name: "Institut für Informatik",
        ins_city: "Kiel"
    }, "json");
    institute.done(function(data) {
        alert(data);
        var ins_data = $.parseJSON(data); // <-- throws syntax error
        $("#street").empty().val(ins_data['ins_street']);
        $("#number").empty().val(ins_data['ins_number']);
        $("#postalcode").empty().val(ins_data['ins_postal_code']);
    }, "json");
    institute.fail(function(data) {
        console.log("Retrieving institute data failed. Returned:"+data);
    });
上面我警告返回的字符串,并告诉我它是有效的JSON

因此,我将字符串直接复制到parseJSON()调用中。很好。为什么不使用变量呢

以下是我尝试过的:

  • 我经常读到缺少单引号/双引号的文章。这里运气不好。在字符串周围添加了多个变体
  • 我还经常读到,在这种环境中不需要parseJSON函数。所以我放弃了函数调用。语法错误当然会消失,但我无法将JSON作为普通数组读取,因此字段只是清空
  • 我尝试用.ajax()替换.post()函数,添加缺少的参数。。。同样的效果
  • 我将数据类型属性更改为html或文本。又没运气了

您添加了
,“json”)
发送到您的
$。post
呼叫。这告诉jQuery为您解析JSON。您的
数据
参数已经是一个对象,无需使用
$.parseJSON
。尝试使用
控制台.log(data)
警报
不是一个很好的调试工具)。这是我以前尝试过的。但是如何使用数组呢?字段一直被清空。您得到的确切错误是什么?SyntaxError:JSON.parse:意外字符
{"ins_name": "Institut für Informatik",
 "ins_street": "HRSl",
 "ins_number": "42",
 "ins_postal_code": "24118",
 "ins_city": "Kiel"}