[英]jQuery $.post processing JSON response
我無法弄清楚如何從 jQuery $.post() 請求中正確讀取我的 JSON 響應。
在下面的 jQuery 代碼中,我根據用作鍵的相應“color_entry_id”從 DOM 中的元素填充了一個關聯字符串數組:
var image_links = {};
$(this).find('input[name="color_id"]').each(function() {
var color_entry_id = $(this).val();
var image_link = $(this).parent().find('input[name="edit_image"].' + color_entry_id).val();
image_links[color_entry_id] = image_link;
});
然后我發出 POST 請求,發送我的“image_links”數組:
$.post(
"test.php",
{ id: product_id, "images[]": jQuery.makeArray(image_links) },
function(data) {
var response = jQuery.parseJSON(data);
$.each(response.images, function(index, item) {
alert(item);
});
}
);
此外,如上所示,我嘗試遍歷響應數組並輸出每個項目,我希望將其作為字符串,但我只得到“[object Object]”作為警報值。 我不知道如何讓它顯示我想要顯示的字符串!
這是 test.php 的 PHP 代碼:
<?php
$product_id = $_POST['id'];
$images = $_POST['images'];
$response = array();
$response['id'] = $product_id;
$response['images'] = $images;
echo json_encode($response);
?>
這是 DOM 的相關部分的樣子:
<input type='hidden' value='{{ color_entry_id }}' name='color_id' />
<p><img src='{{ color_img_link }}' /></p>
<p>Image Link: <input class='{{ color_entry_id }}' name='edit_image' type='text' size='150' value='{{ color_img_link }}' /></p>
<div class='colors {{ color_entry_id }}'>
<div class='img_color'>
<a href='javascript:void' style='background:...' class='selected'></a>
<p>...</p>
</div>
</div>
我想知道我是否在 PHP 端錯誤地執行了 JSON 編碼,或者我是否只是在 jQuery 中錯誤地循環響應。 任何幫助深表感謝!!
好吧..你從帖子中得到的數據對象是: {"id":"abc","images":[{"color123":"somelink.com\\/123","color223":"somelink.com\\/223"}]};
如果您更改提醒,您將找到您正在尋找的值:
$.post(
"test.php",
{ id: product_id, "images[]": jQuery.makeArray(image_links) },
function(data) {
var response = jQuery.parseJSON(data);
var images = response.images[0];
for (var i in images){
alert(images[i]);
}
}
);
$.post 默認期望xml,需要指定響應格式
$.post(
"test.php",
{ id: product_id, images : jQuery.makeArray(image_links) },
function(response) {
// Response is automatically a json object
for(var i = 0; i < response.images.length; i++) {
alert(response.images[i]);
}
}, 'json' // <-- HERE
);
另外,考慮在你的 php 腳本中添加一個內容類型標題
<?php
header("Content-type: application/json"); // Adding a content type helps as well
$product_id = $_POST['id'];
$images = $_POST['images'];
$response = array();
$response['id'] = $product_id;
$response['images'] = $images;
echo json_encode($response);
?>
一個非常基本的例子是這樣的:
$.post('test.php', {"id": 42}, function (json) {
console.log(json);
}, 'json');
PHP 示例
$number = rand(1,$_POST["id"]);
return print json_encode($number);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.