2016-07-14 21 views
0

早上好JSON數據,充分利用鏈接

我有這個簡單的代碼:

<!DOCTYPE html> 
<html lang="en"> 

<head> 
<meta charset="UTF-8"> 
<title>READ JSON Example (AJAX)</title> 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 
    $.ajax({ 
     type: "GET", 
     url: "http://phonegappro.esy.es/test/json.php", 
     crossDomain: true, 
     cache: false, 
     success: function (result) { 
      var result = $.parseJSON(result); 
      $.each(result, function (i, field) { 
       $("#output").append("Title: " + field.title + " duration: " + field.duration + " Price:" + field.price + "<br/>"); 
      }); 
     } 
    }); 
}); 
</script> 
</head> 
<body> 
<div id="output"> 

</div> 
</body> 
</html> 

試圖從JSON獲取數據。我有兩個json鏈接。

  1. http://www.bonar.si/api/restaurants.php
  2. http://phonegappro.esy.es/test/json.php

第二個工作,但第一個是我需要的,是行不通的。他們幾乎是一樣的。第一個問題似乎有問題?也許是因爲它更大的文件?

謝謝!

+0

'幾乎不適合這裏。響應格式應該是'相同的' –

+0

嘗試使用contentType作爲'application/json'和dataType'json'' – patilprashant6792

+0

[同源策略](https://developer.mozilla.org/en-US/docs/Web/安全/同-origin_policy)。第二臺服務器支持[CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)('Access-Control-Allow-Origin:*')。 – Andreas

回答

0

如果你看一下控制檯,您得到消息

「的XMLHttpRequest無法加載http://www.bonar.si/api/restaurants.php。 沒有‘訪問控制允許來源’標頭出現在請求 資源。因此,原產地‘空’是不允許訪問「。

首先,打開運行窗口,輸入-> chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security。然後在新打開Chrome瀏覽器窗口。這爲我工作執行代碼。

<html lang="en"> 

<head> 
<meta charset="UTF-8"> 
<title>READ JSON Example (AJAX)</title> 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
      $.getJSON("http://www.bonar.si/api/restaurants.php", function(result){ 
      $.each(result, function(i, field){ 
      $("#output").append("Name: "+ field.name + " address: "+field.address +" Price:"+field.price+"<br/>"); 
      }); 
      }); 
    }); 
</script> 
</head> 
<body> 
    <div id="output"> 

    </div> 
</body> 
</html> 
+0

由於安全功能,某些內容不起作用。解決方案:完全禁用安全功能... O.o – Andreas

+0

它工作,如果我禁用安全功能,但它有可能做到這一點「正確」的方式? – Chufta

0

我聯繫了服務器所有者,他啓用了CORS,所以它現在正在工作!