【发布时间】:2016-05-24 10:27:00
【问题描述】:
我有一个 ruby 服务器正在运行,它返回以下格式的 JSON:-
{"id":7,"user_name":"logix_5","first_name":"sadf","last_name":"sdgdg","email":"lo@hi.com","password":"l5","phone_number":"123876","user_type":"Manager","job_title":"dfhst","created_at":"2016-05-24T02:52:23.000Z","updated_at":"2016-05-24T06:52:28.000Z"}
当我们转到链接时
http://192.168.68.211:3000/vlapi/login?user_name=logix_5&password=l5
我希望能够从网站访问 JSON 数据并使用纯 JS 从中提取数据。我已经尝试了以下代码:-
var res = new XMLHttpRequest();
var url = "http://128.199.68.211:3000/vlapi/login? user_name=logix_5&password=l5"
res.open("GET",url,true)
res.send()
document.write("Working")
document.write(res.responseText)
我已经尝试过How to get JSON from URL in Javascript? 中给出的代码以及其他一些类似的问题,但“res.responseText”没有返回任何内容。我在代码中遗漏了什么。
注意:代码必须与 QML 一起集成
编辑: 我尝试将https://stackoverflow.com/a/35970894/5608864中给出的代码修改为
getJSON("http://192.168.68.211:3000/vlapi/login?user_name=logix_5&password=l5",
function(err, data) {
if (err != null) {
alert("Something went wrong: " + err);
} else {
alert("Your query count: " + data.query.id);
}
});
控制台中仍然没有打印任何内容。
编辑 我使用https://www.hurl.it/ 向“http://192.168.68.211:3000/vlapi/login?user_name=logix_5&password=l5”发出 GET 请求
它会返回类似这样的响应
Cache-Control: max-age=0, private, must-revalidate
Connection: Keep-Alive
Content-Length: 252
Content-Type: application/json; charset=utf-8
Date: Tue, 24 May 2016 11:07:15 GMT
Etag: W/"30fc28a52d407ac1074eb62d7da0b5d0"
Server: WEBrick/1.3.1 (Ruby/2.3.1/2016-04-26)
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: c7a0d898-da00-4325-99ff-3164d9e03cf4
X-Runtime: 0.017905
X-Xss-Protection: 1; mode=block
BODY view raw
{
"id": 7,
"user_name": "logix_5",
"first_name": "sadf",
"last_name": "sdgdg",
"email": "lo@hi.com",
"password": "l5",
"phone_number": "123876",
"user_type": "Manager",
"job_title": "dfhst",
"created_at": "2016-05-24T02:52:23.000Z",
"updated_at": "2016-05-24T06:52:28.000Z"
}
这对调试问题有帮助吗?能否请您留下代码 sn-p 以获取 JSON。
【问题讨论】:
-
你的请求是异步的,所以你需要使用
res.onreadystatechange来检查响应:How to get the response of XMLHttpRequest? -
你说你看过另一个问题,但你的代码看起来不像code in the other question??!为什么?
-
@Liam 我尝试了链接中给出的代码,但仍然无法解决问题
标签: javascript json qml