【问题标题】:how to set jsonp callback in retrieving restful web service data via jquery如何在通过jquery检索restful web service数据时设置jsonp回调
【发布时间】:2012-03-08 11:57:32
【问题描述】:

我问了一个关于 firebug 上的无效标签的问题,当我尝试从我的 restful 网络服务中检索数据时会发生这种情况。我收到的大多数答案都是关于设置回调函数。但我似乎无法从中获得正确的果汁。你能告诉我一个关于如何做的确切代码吗?或至少在此处更正代码:

        type: "GET",
        cache: false, 
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        processdata:true,
        jsonp: false, jsonpCallback: "success",
        url: 'http://localhost:8732/Service1/data/10',

        success : function success(data) {
            jsonResponse = eval("(" + data + ")");
            alert(jsonResponse)
        },
        error : function(req,status, ex) {

            alert(ex);
        }

谢谢,

【问题讨论】:

    标签: json rest jquery jsonp


    【解决方案1】:

    哇,那里有很多不必要的东西。试试这个:

    $.ajax({
        url: 'http://localhost:8732/Service1/data/10',
        dataType: 'jsonp',
        error: function(req, status, ex) {
            // your code here
        },
        success: function(data) {
            //your code here
            // Please note: you don't need to 'eval' the json response.
            // The 'data' variable will be loaded with the object that the json string represents.
            // By the way, don't use 'eval', ever.
        }
    });
    

    jQuery 会处理 url 上的回调。见这里:http://api.jquery.com/jQuery.ajax/

    更新 为什么是jsonp?如果你是从 localhost 获取的,为什么不只是 json?正如下面的 cmets 中所讨论的,您的服务器目前无法进行 jsonp 响应,但可以进行 json。

    【讨论】:

    • 感谢您的回答。但我仍然有相同的结果。 firebug 上的无效标签 {"Id":10,"Name":"Leo Messi"}。有什么想法吗?
    • 你不是evaling 在success 函数中吗?请显示一些修改后的代码。
    • 这是我使用的代码。我读过关于 eval 的东西。是的,我没有评估成功。 $.ajax({ url: 'localhost:8732/Service1/data/10', dataType: 'jsonp', 错误: function(req, status, ex) { alert("hi"); }, 成功: function(data) { console.log(数据); } });
    • data 不是字符串。它是一个对象。这就是console.log() 窒息的原因吗?更新:不,不是,因为该函数接受对象。你能提供更多信息吗?
    • 我想是的。抱歉,我对 json 真的很陌生。我正在学习它。我只想通过警报或控制台以某种方式显示数据。你能给我一个关于这个的见解吗?感谢您的快速回复。更新:我认为就是这样。错误是无效标签,它在 { 和 ID 中间有一个指向 {"Id":10,"Name":"Leo Messi"} 的小箭头。希望对您有所帮助。
    猜你喜欢
    • 2012-08-16
    • 2023-03-12
    • 1970-01-01
    • 2020-03-20
    • 2016-02-14
    • 1970-01-01
    • 2012-07-31
    • 2013-01-09
    • 2013-01-09
    相关资源
    最近更新 更多