[英]Jquery and ajax How to parse json?
I'm using Jquery and ajax. 我正在使用Jquery和Ajax。
I have a simple form and my jquery : 我有一个简单的表格和我的jQuery :
This is a piece of the code : 这是一段代码:
username = $('input[name="username"]').val();
$.post("api.php", {username: username}, function(data) {
if(data == "error") {
data("erreur");
} else {
alert(data);
$('input[name="subscribers"]').attr("placeholder", "something").blur();
$('input[name="viewCount"]').attr("placeholder", "something").blur();
}
});
And the result of alert(data);
和alert(data);
的结果alert(data);
{"total":"628729","abo":"1646"}
I would like to put the result of total and the result of abo into my placeolder : 我想提出的总的结果和ABO到我placeolder的结果:
$('input[name="subscribers"]').attr("placeholder", ?abo?).blur();
But i don't know who to recover the result of the json and take the value of total and abo 但是我不知道谁能恢复json的结果并取total和abo的值
note : my json is genrate by the file api.php with json_encode
注意:我的json由文件api.php用json_encode
jQuery appears to be trying to handle your JSON as text (or, more likely, HTML). jQuery似乎正在尝试将JSON作为文本(或更可能是HTML)处理。
Tell jQuery that it is JSON: 告诉jQuery它是JSON:
<?php header("Content-Type: application/json"); ?>
Then you can just: 然后,您可以:
foo = data.total
Try this: 尝试这个:
if (data) {
data = JSON.parse(data);
$('input[name="subscribers"]').attr("placeholder", data.abo).blur();
}
You can use $.parseJSON()
to parse json 您可以使用$.parseJSON()
解析json
username = $('input[name="username"]').val();
$.post("api.php", {username: username}, function(data) {
if(data == "error") {
data("erreur");
} else {
alert(data);
data=$.parseJSON(data); // add this line
$('input[name="subscribers"]').attr("placeholder", "something").blur();
$('input[name="viewCount"]').attr("placeholder", "something").blur();
}
});
JSON is a string representing (in this case) an object, so data
is a string. JSON是表示(在这种情况下)对象的字符串,因此data
是字符串。 In order to go from the string to the object you need to parse it. 为了从字符串转到对象,您需要对其进行解析 。 There's a JSON.parse()
function to do that: 有一个JSON.parse()
函数可以做到这一点:
if(data == "error") {
data("erreur");
} else {
alert(data);
var yourObj = JSON.parse(data);
$('input[name="subscribers"]').attr("placeholder", yourObj.abo).blur();
$('input[name="viewCount"]').attr("placeholder", yourObj.subscribers).blur();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.