如何读取AJAX响应变量
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
属性?
您可能可以利用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
。
相关文章:
- 不再使用innerHTML进行AJAX响应.(代码未得到响应)
- 为什么可以't我使用了AJAX响应的一部分
- Ajax响应转换
- 如何在数据表中设置从Ajax响应选中的复选框
- 在Javascript中的ajax响应之后未调用Dropdown事件
- RubyonRails-Ajax响应的问题
- Ajax:Ajax响应中的链接不起作用
- 如何执行ajax响应返回的javascript函数
- 带有 AJAX 响应或 AJAX 响应的 IF 条件.响应.Text 不起作用
- 正在检查ajax响应中的错误数据
- 如何从ajax响应中重新加载整个页面
- 如何使用jQuery/Ajax响应特定的提交按钮
- 是浏览器在AJAX响应中自动处理的HTTP标头
- Masony无法处理ajax响应
- 使用yii2表单等待ajax响应
- jquery返回ajax响应和用户定义的变量到函数
- 使用Ajax响应更新TextBox
- 如何在jquery ajax响应后设置jquery滑块的起始值
- Rails 4中不执行Ajax响应
- jquery解析ajax响应