iron-ajax 响应 returns 空 php json 响应
iron-ajax response returns null for php json response
我是 polymer 1.0 的初学者,使用以下代码我试图在 iron-ajax 开启时从我的 php 文件中获得 json 响应-响应触发器。我通过编辑 php 尝试了不同的响应,但它总是在我的控制台日志中显示为 null。
ajax部分代码
<iron-ajax
id="ajax"
method="POST"
url="post_tip.php"
handle-as="json"
on-response="postResponse"
>
</iron-ajax>
编写部分代码来处理响应
postResponse: function(r){
console.log(r.detail.response);
if(r.detail.response.success==1){
console.log('Tip posted');
}
else{console.log('Error occured.not posted');}
}
我找不到任何错误,但 r.detail.response
returns 每次都是 null。
我的 php 我有。
$resp = '{"success":1}';
echo $resp;
echo json_encode($resp);
不知道我做错了哪一部分。抱歉可能是个愚蠢的问题。
你在 php 中做错了。首先 json_encode
will encode an array or an object to json string, it will escape your string, but thats not that what you want. Secondly you returning twice without [ ]
bracket which cannot be parsed with JSON.parse
or cannot be used as a JSON Object
在 javascript.
你应该发回 JSON content-type
,因为响应可能不是 hooked trough JSON.parse
, and expecting a real JSON
, but on the iron-ajax documentation the handle-as="json"
意味着:
json: uses XHR.responseText parsed as JSON.
因此 iron-ajax
元素使用 JSON.parse
on the XHR.responseText
to parse the JSON
作为 object,这意味着 PHP header 不是必需的,但您应该使用。
像这样更改您的 php 代码:
<?php
$result = array('success' => 1);
header('Content-Type: application/json');
echo json_encode($result);
我是 polymer 1.0 的初学者,使用以下代码我试图在 iron-ajax 开启时从我的 php 文件中获得 json 响应-响应触发器。我通过编辑 php 尝试了不同的响应,但它总是在我的控制台日志中显示为 null。 ajax部分代码
<iron-ajax
id="ajax"
method="POST"
url="post_tip.php"
handle-as="json"
on-response="postResponse"
>
</iron-ajax>
编写部分代码来处理响应
postResponse: function(r){
console.log(r.detail.response);
if(r.detail.response.success==1){
console.log('Tip posted');
}
else{console.log('Error occured.not posted');}
}
我找不到任何错误,但 r.detail.response
returns 每次都是 null。
我的 php 我有。
$resp = '{"success":1}';
echo $resp;
echo json_encode($resp);
不知道我做错了哪一部分。抱歉可能是个愚蠢的问题。
你在 php 中做错了。首先 json_encode
will encode an array or an object to json string, it will escape your string, but thats not that what you want. Secondly you returning twice without [ ]
bracket which cannot be parsed with JSON.parse
or cannot be used as a JSON Object
在 javascript.
你应该发回 JSON content-type
,因为响应可能不是 hooked trough JSON.parse
, and expecting a real JSON
, but on the iron-ajax documentation the handle-as="json"
意味着:
json: uses XHR.responseText parsed as JSON.
因此 iron-ajax
元素使用 JSON.parse
on the XHR.responseText
to parse the JSON
作为 object,这意味着 PHP header 不是必需的,但您应该使用。
像这样更改您的 php 代码:
<?php
$result = array('success' => 1);
header('Content-Type: application/json');
echo json_encode($result);