使用JavaScript从网站获取JSON

时间:2016-05-24 10:27:01

标签: javascript json qml

我运行的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"
}

这对调试问题有帮助吗?你能留下一段代码片段来获取JSON。

5 个答案:

答案 0 :(得分:1)

Ajax请求是异步的,因此在调用时不会设置res.responseText。您必须使用事件处理程序:

res.addEventListener('load', function () {
    console.log(res.responseText)
})

答案 1 :(得分:0)

你在网址中有空格。

更改此行:

var url = "http://128.199.68.211:3000/vlapi/login? user_name=logix_5&password=l5"

要:

 var url = "http://128.199.68.211:3000/vlapi/login?user_name=logix_5&password=l5" 

答案 2 :(得分:0)

我在代码中看到的第一个问题是删除user_name参数之前的前导空格。

然后,当答案回来时,我会在一个对象中转换你的答案:

res.addEventListener('load', function () {
    console.log(res.responseText);
    obj = JSON.parse(res.responseText);
})

答案 3 :(得分:0)

您在问题中提到的两个网址都是不同的,即使两者都没有返回任何内容也接受错误消息无法访问网站,如果您的服务器来自您尝试获取响应的话无法尝试打开它 或者服务器端可能存在一些程序错误。 它应该工作

答案 4 :(得分:0)

首先请确保json响应有效。您可以使用http://jsonlint.com/

对于QML,我通常使用干净的代码和可重用性一组三个函数:一个帮助器,一个调用者和一个回调函数。

在这个简短的例子中,我使用了上面其他SO问题的yahoo链接。通过点击" Hello World",调用者jsonYahoo运行,jsonYahooCallback response result包含答案字符串,而import QtQuick 2.3 import QtQuick.Window 2.2 Window { visible: true MouseArea { anchors.fill: parent onClicked: { jsonYahoo() } } Text { id: hello text: qsTr("Hello World") anchors.centerIn: parent } function jsonYahoo() { var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback" var data = '' request(url, data, jsonYahooCallback) } function jsonYahooCallback(success, response) { var result = JSON.parse(response) if (success === true) { console.log(response) hello.text = result.query.created } else { console.log("request failed") } } function request(url, data, callback) { var xhr = new XMLHttpRequest() xhr.open('POST', url, true) xhr.setRequestHeader('Content-Type', 'application/json') xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status && xhr.status === 200) { callback(true, xhr.responseText) } else { callback(false, xhr.responseText) } } } xhr.send(data) } } 包含解析的json。

结果:

before in qm after in qml

代码:

   function classesForNbhds() {
        $('.nbhds-overlay h3').each(function(i,s) {
          $(this).addClass('myclass'+(i+1));
        });
    }