跨域获取ajax请求正在抛出解析错误

时间:2013-04-25 06:53:58

标签: javascript jquery cross-domain

$.ajax({
                type: "GET",
                url: "http://api.zip-tax.com/request/v20",                    
                data: {
                    key: '1234567890',
                    postalcode: '90265',
                    format: 'json'
                },
                success: function (json) {
                    debugger;
                    // do stuff with json (in this case an array)
                    alert("Success");
                },
                error: function (a, b, c) {
                    debugger;
                    alert("Error");
                }
            });

当我运行上面的代码时,它会将我抛出错误块并说

SyntaxError: invalid label
[Break On This Error]   

{"version":"v20","rCode":100,"results":[{"geoPostalCode":"902

虽然它也显示readyState=4, status=200, statusText="success"parsererror 如果我点击那个网址,我可以看到正确的json

URL: `http://api.zip-tax.com/request/v20?key=1234567890&postalcode=90265&format=json`
Result: `{"version":"v20","rCode":100,"results":[{"geoPostalCode":"90265","geoCity":"MALIBU","geoCounty":"LOS ANGELES","geoState":"CA","taxSales":0.090000003576279,"taxUse":0.090000003576279,"txbService":"N","txbFreight":"N","stateSalesTax":0.064999997615814,"stateUseTax":0.064999997615814,"citySalesTax":0,"cityUseTax":0,"cityTaxCode":"","countySalesTax":0.0099999997764826,"countyUseTax":0.0099999997764826,"countyTaxCode":"19","districtSalesTax":0.014999999664724,"districtUseTax":0.014999999664724},{"geoPostalCode":"90265","geoCity":"PT DUME","geoCounty":"LOS ANGELES","geoState":"CA","taxSales":0.090000003576279,"taxUse":0.090000003576279,"txbService":"N","txbFreight":"N","stateSalesTax":0.064999997615814,"stateUseTax":0.064999997615814,"citySalesTax":0,"cityUseTax":0,"cityTaxCode":"","countySalesTax":0.0099999997764826,"countyUseTax":0.0099999997764826,"countyTaxCode":"19","districtSalesTax":0.014999999664724,"districtUseTax":0.014999999664724},{"geoPostalCode":"90265","geoCity":"TWAIN HARTE","geoCounty":"VENTURA","geoState":"CA","taxSales":0.075000002980232,"taxUse":0.075000002980232,"txbService":"N","txbFreight":"N","stateSalesTax":0.064999997615814,"stateUseTax":0.064999997615814,"citySalesTax":0,"cityUseTax":0,"cityTaxCode":"","countySalesTax":0.0099999997764826,"countyUseTax":0.0099999997764826,"countyTaxCode":"56","districtSalesTax":0,"districtUseTax":0}]}`

请指教。我不想写服务器端脚本。

1 个答案:

答案 0 :(得分:2)

这不是JSONP的工作原理。

使用正确的JSONP,会在页面上放置<script>元素,并将src设置为您要求的网址。这是由jQuery在内部处理的。

JSONP的响应是不是 JSON。它是JavaScript,调用函数,并将JSON作为参数传递。这就是允许跨域数据传输的方式,因为您只需要请求Javascript代码。

在发出请求时,您必须提供要使用JSON响应调用的函数的名称,通常如下:

http://www.website.com/request/jsonp?param=value&param2=value2&callback=callbackFunc

因此,回复的格式为:

callbackFunc({JSON stuff});

jQuery在内部处理这个回调函数,以便最终调用success方法。

它看起来不像API支持JSONP(http://www.zip-tax.com/documentation),因此您必须对您自己的服务器进行AJAX调用,让该服务器发出您需要的请求(返回JSON),并在AJAX响应中返回JSON。