2017-10-11 153 views
0

嗨我正在嘗試使用僅限 JavaScript和HTML從URL中獲取JSON對象。我使用下面的代碼:跨域JSON Javascript

<html> 
<head> 
    <title>Json</title> 
    <script src="jquery-3.2.1.min.js"></script> 
</head> 
    <body> 
     <button onclick="myFunction()">Start</button> 

     <script> 
     function myFunction() { 
      jQuery.ajax({ 
       url: 'https://iotmmss0018275632trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/app.svc/T_IOT_59824470F0BD12350F22?$format=json', 
       type: 'GET', 
       crossDomain: true, 
       dataType: 'json', 
       success: function(response) { 
        console.log(response); 
       }, 
       error : function(error) { 
        console.log(error); 
       }, 
      }); 
     } 
     </script> 

    </body> 

正如預期的那樣,我越來越

Failed to load "URL": No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost ' is therefore not allowed access. The response had HTTP status code 401.

我不能配置服務器,我不知道它是否支持CORS(林新)。我嘗試了JSONP請求,並得到了爲響應狀態代碼200和JSON,但與錯誤:

Uncaught SyntaxError: Unexpected token :

所以,我該怎麼辦?

+0

api是否有文檔?它是否說它支持jsonp? –

+0

我可以得到兩種不同格式的數據:xml和json。我試過jsonp請求,因爲它沒有得到錯誤的唯一方法:未能加載「URL」:沒有'訪問控制允許源'頭... –

+0

只有API支持jsonp,它不一樣作爲香草json。如果您無法控制服務器(以添加cors支持),則可以創建自己的服務器以代理針對您的api調用。 –

回答

0

你應該嘗試通過這個答案here。它詳細介紹了這個主題。

P.S .:應該評論這個,但不能,因爲我沒有所需的聲望點。