如何读取AJAX响应变量

How to read AJAX response variable?

本文关键字:AJAX 响应 变量 读取 何读取      更新时间:2023-09-26

以下是我在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属性?

您可能可以利用jQuery的getJSON方法。当您使用ajax时,您只收到一个字符串响应,因此您首先必须使用parseJSON将其解析为json。但是,getJSON将为您解析JSON。

$.getJSON('my/service', function(data) {
    $('#myimage').attr('src', data.url);
});

yo可以使用

x=$.parseJSON(response)

这将把json字符串转换为一个有效的json-objet,如果出现错误,将抛出一个异常,您可以使用try{}catch(e)}来修复它

try{
var x=$.parseJSON(response);
}catch(e){
console.log(e);
}

使用JSON.parse作为对象进行解析,返回的数据为字符串:

response=JSON.parse(response);
$( '#myimage' ).attr( 'src', response.data.url );

简单的方法是使用这样的AJAX请求:

$.post('remote_url', {key:value}, function(response){
    if(response.success) {
        $('#myimage').attr('src', response.data.url);
    }
}, 'json');

在本例中,我使用了$.post,但您没有提供足够的关于请求类型的信息,因此它也可能是$.getJSON请求。此外,{key:value}是一个对象,如果需要,它将被传递给服务器。所以,如果您将任何数据传递给服务器,请使用它,否则将其删除

在本例中,'json'被用作数据类型,因此响应将由jQuery解析。如果您使用$.getJSON,则响应将被解析,但在这种情况下,您不需要使用'json'作为最后一个参数。例如:

$.getJSON('remote_url', function(response) {
    if(response.success) {
        $('#myimage').attr('src', response.data.url);
    }
});

注意:getJSON使用GET HTTP请求从服务器加载JSON编码的数据。因此,对于POST请求,请改用$.post