[英]How to read AJAX response variable?
以下是我在AJAX成功函数中收到的响应:
"{"success":true,"data":{"id":1841,"title":"atitle","filename":"filename.jpg","url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename.jpg","link":"http:\/\/example.com\/?attachment_id=1841","alt":"","author":"21","description":"","caption":"","name":"filename-39","status":"inherit","uploadedTo":0,"date":1415555051000,"modified":1415555051000,"menuOrder":0,"mime":"image\/jpeg","type":"image","subtype":"jpeg","icon":"http:\/\/example.com\/wp-includes\/images\/media\/file.png","dateFormatted":"November 9, 2014","nonces":{"update":"b832c2939d5","delete":"83dda46357e","edit":"51ac41b11c6"},"editLink":"http:\/\/example.com\/wp-admin\/post.php?post=1841&action=edit","meta":false,"authorName":"Some One","filesizeInBytes":10755,"filesizeHumanReadable":"11 kB","sizes":{"thumbnail":{"height":90,"width":90,"url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename-90x90.jpg","orientation":"landscape"},"full":{"url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename.jpg","height":260,"width":236,"orientation":"portrait"}},"height":260,"width":236,"orientation":"portrait","compat":{"item":"","meta":""}}}"
我正在尝试使用此响应中返回的数据更新页面上特定图像的src
属性。 例如:
$( '#myimage' ).attr( 'src', response.data.url );
问题是,我收到错误信息Uncaught TypeError: Cannot read property 'url' of undefined
我确定response.data.url
是错误的。 如何从响应中获取URL,以便可以更新图像的src
属性?
使用JSON.parse解析为对象,您返回的数据为字符串:
response=JSON.parse(response);
$( '#myimage' ).attr( 'src', response.data.url );
哟可以用
x=$.parseJSON(response)
并将json字符串转换为有效的json对象,如果发生错误将引发异常,则可以使用try {} catch(e){}进行修复
try{
var x=$.parseJSON(response);
}catch(e){
console.log(e);
}
简单的方法是使用这样的AJAX
请求:
$.post('remote_url', {key:value}, function(response){
if(response.success) {
$('#myimage').attr('src', response.data.url);
}
}, 'json');
在此示例中,我使用了$.post
,但是您没有提供有关请求类型的足够信息,因此它也可能是$.getJSON
请求。 同样, {key:value}
是一个对象,如果需要,它将被传递到服务器。 因此,如果将任何数据传递到服务器,请使用它,否则将其删除。
在此示例中, 'json'
被用作数据类型,因此如果您使用$.getJSON
则jQuery
也将解析响应,然后将解析响应,但在这种情况下,您无需使用'json'
作为最后一个参数。 例如:
$.getJSON('remote_url', function(response) {
if(response.success) {
$('#myimage').attr('src', response.data.url);
}
});
注意: getJSON
使用GET
HTTP请求从服务器加载JSON编码的数据。 因此,对于POST
请求,请改用$.post
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.