0

我是 node.js 和 json 的新手,无法将 JSON 对象返回到正在使用的客户端 html 页面$.getjson

在下面的示例中,当我将相同的代码指向 api.twitter.... url 时,我可以查询并返回该值。但是当我将它指向我自己的 node.js 后端时,它吐出相同的 JSONalert('inside callback: ' + data[0].is_translator);并不会弹出。我在这里做错了什么?我真的很感激这里的一些帮助。

这是我的 test.html 中调用 $.getJSON 的脚本代码。

<script>
//var url = "http://localhost:5000/searchPlaces?callback=?";
function abc(result) {
//var url = "http://localhost:5000/random"
var url = "http://api.twitter.com/1/statuses/21947795900469248/retweeted_by.json?callback=?";
alert('before $.getjson');
$.getJSON(url, function(data) {
      alert('hello');
      alert('inside callback: ' + data[0].is_translator);
      abc(result.data);
})

}

abc();

</script>

这是来自我的 node.js 后端的代码:

var http = require("http");
var url = require("url");
var port = process.env.PORT || 8888

function start(route, handle){

        function onRequest(request, response) {

                var postData = "";
                var pathname = url.parse(request.url).pathname;

                console.log("Request received for:" + pathname + " receieved.");

          response.writeHead(200, {"Content-Type": "application/json"});
          var otherObject = {"is_translator":false,"id":644233,"followers_count":77};

           response.write(
            JSON.stringify({
              anObject: otherObject
            })
          );
          response.end();

//              route(handle, pathname, response, request);

        }

        http.createServer(onRequest).listen(port);
        console.log("Server had started. Port:" + port);
}

exports.start = start;

4

1 回答 1

0

Callback for $.getJSON() is called only if the JSON is valid. The url for your twitter api http://api.twitter.com/1/statuses/21947795900469248/retweeted_by.json?callback=? gives a JSON with the following error on JSONlint.org

Parse error on line 1:
([    {        "is
^
Expecting '{', '['

You should maybe $.get() the url and then validate JSON yourself before using it.

于 2013-02-20T17:02:27.687 回答