[英]Decoding json object in javascript that is returned from ajax
我已經用json_encode在php中為ajax返回准備了一個數組。 通過ajax返回時,它的行為不符合我的預期。
$.ajax({
url:"dbpaginate.php",
type:"POST",
data: {'environmentvars': tmp},
cache: false,
success: function(response){
alert('Returned from ajax: ' + response);
alert(response["actionfunction"]);
$j.each(response, function (index,element) {
alert(index);
alert(element);
});
});
Returned from ajax: array(5) {
["actionfunction"]=>
string(8) "showData"
["sortparam"]=>
string(6) "ticker"
["sortorder"]=>
string(3) "ASC"
["page"]=>
int(1)
["htmlstring"]=>
string(0) ""
}
{"actionfunction":"showData","sortparam":"ticker","sortorder":"ASC","page":1,"htmlstring":"","htmltext":"<table id=\"summaryheader\"> [...lots of html...]<\/div>\n"}
undefined
showData
如何有效地將json response
移植到javascript對象environmentvars中? 謝謝。
您必須使響應為有效的JSON。 似乎您在服務器端腳本中的某處有一條print_r
語句,其輸出包含在響應中。 刪除它。
響應始終是文本,即JavaScript中的字符串。 您可以在添加數據之前解析JSON(在JavaScript中解析JSON? ),或者通過添加dataType: 'json'
選項告訴jQuery為您解析。
您應該在此類方法中指定一個dataType參數,該參數基本上用於聲明您希望從服務器獲取的數據類型。
這是一個例子:
$.ajax({
type: "POST",
url: <your-request-url>,
data: <your-data>,
success: function(){ ... },
dataType: "json"
});
此處有更多詳細信息: https : //api.jquery.com/jquery.post/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.