好吧,我有一个 php
文件,当邮政编码被发布
到它时,它会发送一个 get
请求来检索一些JSON
数据。
JSON
输出如下:
[{"AddressLine1":"West George Street","AddressLine2":null,"City":"Glasgow","County":"Lanarkshire","HouseName":"1","HouseNumber":"48","Postcode":"G21BP"},{"AddressLine1":"West George Street","AddressLine2":null,"City":"Glasgow","County":"Lanarkshire","HouseName":"3","HouseNumber":"48","Postcode":"G21BP"},{"AddressLine1":"West George Street","AddressLine2":null,"City":"Glasgow","County":"Lanarkshire","HouseName":"2","HouseNumber":"48","Postcode":"G21BP"},{"AddressLine1":"West George Street","AddressLine2":null,"City":"Glasgow","County":"Lanarkshire","HouseName":null,"HouseNumber":"46","Postcode":"G21BP"}]
我在 php
页面上使用 print_r($result);
来显示结果
编辑
我的输出的 HTML 看起来像这样:
<html>
<head></head>
<body>
<pre>[{"AddressLine1":"Garelochhead","AddressLine2":null,"City":"Helensburgh","County":"Argyll And Bute","HouseName":null,"HouseNumber":"","Postcode":"G840EG"},{"AddressLine1":"Garelochhead","AddressLine2":null,"City":"Helensburgh","County":"Argyll And Bute","HouseName":"1","HouseNumber":"Flat 0","Postcode":"G840EG"},{"AddressLine1":"Garelochhead","AddressLine2":null,"City":"Helensburgh","County":"Argyll And Bute","HouseName":"1","HouseNumber":"Flat 1","Postcode":"G840EG"}]
</body>
</html>
<小时/>
我的 JS 目前如下所示:
$('.btnFind').click(function() {
var dataString;
$.ajax({
url:baseUrl+'/postcode.php',
type: 'post',
datatype: "JSON",
data: dataString,
success: function() {
//test
}
}).error (function() {
alert('error with finding your address');
}).complete (function(data) {
console.log(data);
//var AddressLine1 = data[0].AddressLine1,
// AddressLine2 = data[0].AddressLine2,
// City = data[0].City,
//County = data[0].County,
// HouseName = data[0].HouseName,
// HouseNumber = data[0].HouseNumber;
alert(data[0].AddressLine1);
});
});
但我不断收到以下错误:
Uncaught TypeError: Cannot read property 'AddressLine1' of undefined
我的猜测是 print_r 不合适,但说实话,自从我使用 JSON 以来已经有一段时间了,所以公平地说,我还没有达到标准。
如果这也有什么区别的话,它也会打印在一个空白的 html 页面上。
<小时/>按要求控制台日志
Object
abort
:
(a)
always
:
()
complete
:
()
done
:
()
error
:
()
fail
:
()
getAllResponseHeaders
:
()
getResponseHeader
:
(a)
overrideMimeType
:
(a)
pipe
:
()
progress
:
()
promise
:
(a)
readyState
:
4
responseText
:
""
setRequestHeader
:
(a,b)
state
:
()
status
:
200
statusCode
:
(a)
statusText
:
"OK"
success
:
()
then
:
()
__proto__
:
Object
最佳答案
在引用你的对象之前,应该先欢迎该对象。 试试这个
data = JSON.parse(data);
alert(data[0].AddressLine1);
关于javascript - jQuery Ajax POST 获取 JSON 并返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42902776/