[英]put JSON response in var and output it
I have a form which sends Zip code + housenumber to an external page and the external page sends me a json response with the address information back. 我有一个将邮政编码+门牌号发送到外部页面的表单,该外部页面向我发送了一个json响应,并返回了地址信息。
This all works but how can i grab this json response put it into a variable and output it again on my page. 所有这些都有效,但是我该如何获取这个json响应,将其放入变量中并再次在页面上输出。
Here i do a post to a page 在这里我发布到页面
function validate() {
var postc = $('#postc').val();
var huisnr = $('#huisnr').val();
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false
});
and i get this response in the header of postcodecheck.php 我在postcodecheck.php的标题中收到此响应
{"location":[{"city":"Amsterdam","postcode":"1012NX","straat":"Kalverstraat","nummer":1}]}
How can i grab this reponse and put it into a variable ? 我如何获取此响应并将其放入变量中?
Any help would be highly appriciated. 任何帮助都将得到高度重视。
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false,
success: function(data) {
$.each(data.location, function(index, value) {
console.log("City " + value.city)
console.log("postcode " + value.postcode)
console.log("straat " + value.straat)
})
}
});
Add success and inside success you can iterate on the data 添加成功和内部成功,您可以迭代数据
you can use request callback to get the retrieved data & put it into a variable 您可以使用请求回调获取检索到的数据并将其放入变量中
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false
})
.done(function(data) {
console.log(data);});
The ajax call have another attribute called success
you need to use it. ajax调用还有另一个名为
success
属性,您需要使用它。
var store = '';
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false,
success: function(result){
store = result;
}
});
Result 结果
console.log(store); //{"location":[{"city":"Amsterdam","postcode":"1012NX","straat":"Kalverstraat","nummer":1}]}
You need to use the done
method and pass data
as an argument to the callback function that will then contain the response from the server. 您需要使用
done
方法,并将data
作为参数传递给回调函数,然后该回调函数将包含来自服务器的响应。
$.ajax({
url: 'postcodecheck.php',
type: 'POST',
dataType: 'json',
data: 'postc=' + postc + '&huisnr=' + huisnr,
cache: false
}).done(function(data) {
var result = data;
alert(result);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.