简体   繁体   English

使用 JSONP 的 AJAX 跨域数据

[英]cross-domain data with AJAX using JSONP

I'm trying to get data from Geobytes.我正在尝试从 Geobytes 获取数据。 One of the templates returns JSON and I need to cross-domain access it.其中一个模板返回 JSON,我需要跨域访问它。

I wrote these 2 functions我写了这两个函数

function getCountry(ip) {
    var surl = "http://www.geobytes.com/IpLocator.htm?GetLocation&template=json.txt";
    $.ajax({
        url: surl,
        data: '{"ipaddress":"' + ip + '"}',
        dataType: "jsonp",
        processData: false,
        jsonpCallback: "jsonpcallback",
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}

function jsonpcallback(rtndata) {
    alert(rtndata.message);
}

The call is executed successfully, these are my response headers:调用成功执行,这些是我的响应头:

HTTP/1.1 200 OK
Date: Sat, 17 Nov 2012 12:43:54 GMT
Expires: 0
Content-type: text/html
Transfer-Encoding: chunked

the returned data is JSON, but I get返回的数据是 JSON,但我得到

warning: Resource interpreted as Script but transferred with MIME type text/html: "http://www.geobytes.com/IpLocator.htm?GetLocation&template=json.txt&callback=jsonpcallback&{%22ipaddress%22:%22200.167.254.166%22}&_=1353148931121"警告:资源被解释为脚本但使用 MIME 类型 text/html 传输:“http://www.geobytes.com/IpLocator.htm?GetLocation&template=json.txt&callback=jsonpcallback&{%22ipaddress%22:%22200.167.254.166%22} &_=1353148931121"

Error on the remote IpLocator.htm: Uncaught SyntaxError: Unexpected token :远程 IpLocator.htm 上的错误:Uncaught SyntaxError: Unexpected token :

The error is thrown on the returned data at在返回的数据上抛出错误

{"geobytes":{"countryid":117,

I think is maybe because it's 117 and not "117" but I obviously can't control the returned data.我认为可能是因为它是 117 而不是“117”,但我显然无法控制返回的数据。 Tried to add a "processData=false" but that didn't help.试图添加一个“processData=false”,但这没有帮助。

I've added the error handling to the ajax and get "parsererror" on the status我已将错误处理添加到 ajax 并在状态上获得“解析器错误”

How can I fix this?我怎样才能解决这个问题?

Try to modify the field dataType like this:尝试像这样修改字段 dataType:

...
dataType: "jsonp json",
...

In this way the data yo get will be parsed as json.这样你得到的数据将被解析为json。

Following the documentation:按照文档:

The type of data that you're expecting back from the server.您期望从服务器返回的数据类型。 If none is specified, jQuery will try >to infer it based on the MIME type of the response.如果没有指定,jQuery 将尝试根据响应的 MIME 类型推断它。

In your case the MIME you get is text/html, adding the "json" value to the dataType, you tell jQuery to treat the response as json and not text.在您的情况下,您获得的 MIME 是 text/html,将“json”值添加到 dataType,您告诉 jQuery 将响应视为 json 而不是文本。

If the service do not support JSONP you can make your own proxy page to handle the request, or using YQL as described here: Cross-Domain request when server does NOT support JSONP如果该服务不支持 JSONP,您可以制作自己的代理页面来处理请求,或使用 YQL 如下所述: 服务器不支持 JSONP 时的跨域请求

Thank you to no.andrea for pointing me to the right direction!感谢no.andrea为我指明了正确的方向!

As I'm using MVC3 I've added a new controller当我使用 MVC3 时,我添加了一个新控制器

[HttpPost]
public JsonResult JsonGetCountry(string ip)
{
    try
    {
        var sb = new StringBuilder();
        sb.Append("http://www.geobytes.com/IpLocator.htm?GetLocation");
        sb.Append("&template=json.txt");
        sb.Append("&IpAddress=");
        sb.Append(ip);

        var webClient = new WebClient();
        var data = webClient.OpenRead(sb.ToString());

        if (data == null) { return Json(""); }

        var reader = new StreamReader(data);
        var msg = reader.ReadToEnd();
        data.Close();
        reader.Close();

        return Json(msg);
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message, ex);
    }
}

and updated my JQuery function to并将我的 JQuery 函数更新为

function getCountry(ip) {
    $.ajax({
        type: "POST",
        url: "/My-Shop/IP/JsonGetCountry",
        data: '{"ip":"' + ip + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var a = $.parseJSON(msg);
            alert(a.geobytes.iso2);
        },
        error: function (ex) {
            alert(ex.statusText);
    }
});

And that fixed all my problems :)这解决了我所有的问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM