2016-01-15 114 views
0

我想提出一個Ajax請求WeatherUnderground服務方式如下:未捕獲的SyntaxError:意外的標記:在WeatherUnderground響應

$.ajax({ 
    url : 'http://autocomplete.wunderground.com/aq?query=' + $input.val(), 
    type: 'GET', 
    dataType : "JSONP", 
    success : function(parsed_json) { 
     var obj = JSON.parse(parsed_json); 
     alert(typeof parsed_json); 
     for (var i = 0; i < obj.RESULTS.length; i++) { 
      suggestions[i] = obj.RESULTS[i].name; 
     } 
    }, 
    error : function(parsed_json){ 
     alert('Error'); 
    } 
}); 

但是,當我得到迴應後,我看到下面的錯誤:

未捕獲語法錯誤:意外標記:

而且性反應的第一行加下劃線

{ "RESULTS": [ 
    { 
     "name": "Dakar, Senegal", 
     "type": "city", 
     "c": "SN", 
     "zmw": "00000.1.61641", 
     "tz": "Africa/Dakar", 
     "tzs": "GMT", 
     "l": "https://stackoverflow.com/q/zmw:00000.1.61641", 
     "ll": "14.730000 -17.500000", 
     "lat": "14.730000", 
     "lon": "-17.500000" 
    }, ... 

什麼可能導致此問題?

預先感謝您!

+1

什麼'$ input.val的價值()'? – Steve

+0

我在文本框中輸入的任何東西。在這個特定的例子中,它只是字母d。 –

回答

0

您正在使用JSONP意味着JSONP(帶填充的JSON)它與json不同。 請參閱此鏈接瞭解更多詳情。 鏈接:http://json-jsonp-tutorial.craic.com/index.html

客戶端使用JSONP的唯一更改是向該URL添加回調參數。最簡單的方法是添加'callback =?'在這種情況下,jQuery將生成一個唯一的函數名稱並將其傳遞給服務器。

在服務器上,您需要獲取「回調」參數,而不是返回原始JSON,而是將該字符串包裝在函數定義中,如「()」。您不需要事先知道函數名稱 - 只需從該回調參數中獲取。

您還應該將內容類型設置爲'application/javascript',儘管在我的測試中這似乎不重要。

回到客戶端,您會像處理原始JSON對象一樣處理返回的函數。

`var url = host_prefix + '/jsonp?callback=?'; 

$.getJSON(url, function(jsonp){ $("#jsonp-response").html(JSON.stringify(jsonp, null, 2)); });

這將幫助你。

0

也可能值得一提的是,在wunderground API的情況下,他們提供了一個回調參數,因此您可以通過以下方式完全避免阿賈克斯...

<body> 
<input id="inp"/> 
<input type="button" id="btn" value="Go!"> 
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> 
<script> 
$("#btn").on("click",getDeets); 

function getDeets(){ 
var str=$("#inp").val(); 
if(document.getElementById("myscr")){ 
document.body.removeChild(document.getElementById("myscr")); 
} 
var scr=document.createElement("script"); 
scr.id="myscr"; 
document.getElementById("myscr").src="http://autocomplete.wunderground.com/aq?query="+str+"&cb=myfunc"; 
document.body.appendChild(scr); 
} 

function myfunc(o){ 
console.log(o); 
} 
</script> 
</body> 
相關問題