1

嗨,我正在使用此代码从 json 文件中获取内容,但我无法显示结果

我的代码是

$(document).ready(function(){

$.ajax({
    url: 'http://50.116.19.49/rest/user.json',
    dataType: 'jsonp',
    jsonp: 'jsoncallback',
    timeout: 50000,
    success: function(data, status){
    alert(data);    
    },
    error: function(){
        output.text('There was an error loading the data.');
    }
});
});

在谷歌浏览器中,我可以看到请求状态为 200 并且数据已加载。这是我从中复制代码的链接链接....任何帮助!!!!

谢谢

4

3 回答 3

2

Your code doesn't work because the http://50.116.19.49/rest/user.json resource return a JSON response instead of JSONP (difference).

So you can't make cross-domain calls via ajax BUT you can create a some proxy script ON YOUR SERVER which will make it for you. Example:

cross-domain-call.php

<?php echo file_get_contents('http://50.116.19.49/rest/user.json');?>

And change your script to

$(document).ready(function(){

$.ajax({
    url: 'http://127.0.0.1/cross-domain-call.php',
    dataType: 'json',
    timeout: 50000,
    success: function(data, status){
        console.log(data);    
    },
    error: function(jqXHR, textStatus, errorThrown){
        console.log(jqXHR);    
        console.log(textStatus);    
        console.log(errorThrown);    
    }
});
});
于 2012-10-21T17:24:40.673 回答
0

由于您似乎无法访问远程 Web 服务来将其转换为 JSONP,因此这里有一个使用 Yahoo 的 YQL 作为代理的解决方案。YQL 将从任何远程站点检索文件内容并以 xml 或 jsonp 形式返回。

工作演示 http://jsfiddle.net/Uh8cz/2/

您会注意到响应对象具有由 YQL 创建的其他属性

var yqlBaseUrl = 'http://query.yahooapis.com/v1/public/yql?q=';


var restUrl = 'http://50.116.19.49/rest/user.json';
var yqlQuery = 'select * from json where url="' + restUrl + '" ';
var yqlFormat = 'format=json'
var jQueryCallback = '?'
var fullQueryUrl = yqlBaseUrl + yqlQuery + '&' + yqlFormat + '&' + jQueryCallback;

$.getJSON(fullQueryUrl, function(json) {
    var jsonString = JSON.stringify(json.query.results.json.json, null, ' ')
    $('body').append('<h1>Response</h1><pre>' + jsonString)
})  ​
于 2012-10-21T17:51:53.723 回答
0

如果您可以控制“user.json”的内容,请将其包装在一个函数中:

user.json 内容:

execute_jsonp({you_json)

你的JavaScript:

$(document).ready(function(){

    $.ajax({
        url: 'http://50.116.19.49/rest/user.json',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        timeout: 50000,
        success: function(data, status){
            data(); //execute the function that is sent
        },
        error: function(){
            output.text('There was an error loading the data.');
        }
    });

    function execute_jsonp(json){ //recreate the function so you may access the json as a parameter
        alert(json);
    }
});

希望这可以帮助 ;)

于 2012-10-22T11:45:18.480 回答