2013-06-18 88 views
3

我想使用GET HTTP cal,我得到了使用高級REST客戶端(Chrome plugin)的請求,但無法讓它在JQuery中工作。使用HTTP GET與JQuery

繼從this thread的建議,我已經設置了以下內容:

$(document).ready(function() { 
$('.ap1').click(function(){ 
$.ajax({ 
     url: 'https://api2.panopta.com/v2/monitoring_node/41', 
     type: 'GET', 
     dataType: 'json', 
     success: function() { alert('hello!'); }, 
     error: function() { alert('boo!'); }, 
     beforeSend: setHeader 
    }); 
}); 
function setHeader(xhr) { 
    //extra stuff from REST CLIENT 
    xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY'); 
} }); 

這是我試圖獲得(成功地與REST客戶端)

{ 
url: "https://api2.panopta.com/v2/monitoring_node/41" 
hostname: "phoenix01.monitorengine.com" 
ip_address: "65.23.158.149" 
name: "Phoenix" 
textkey: "na.west.phoenix01" 
} 

我只是輸出希望能夠從該JSON訪問名稱變量並將其傳遞給我的函數。我想至少得到上面的代碼工作之前,我試圖找出如何創建一個對象,所以我可以成功地調用名稱,如.append(object.name)

我剛開始學習JQuery,這是我的第一篇文章很抱歉如果我沒有包含足夠的細節。

+4

[同源策略(http://en.wikipedia.org/wiki/Same_origin_policy) – Musa

回答

1

您不能將ajax調用應用到其他域。您可以通過curl()file_get_content(url)使用服務器到服務器調用,然後對您的腳本進行js調用。

首先使PHP文件,該文件將調用服務器請注意,如果你想使用的file_get_contents你應該在你的php.ini allow_url_fopen選項:

myProxy.php

<? 
$content = file_get_contents($yourUrl); 
// do whatever you want with the content then 
// echo the content or echo params via json 
?> 

您的JS應該撥打電話到PHP,所以你必須解決辦法同一個域策略:

$.ajax({ 
     url: 'myProxy.php', 
     type: 'GET', 
     dataType: 'json', 
     success: function() { alert('hello!'); }, 
     error: function() { alert('boo!'); }, 
     beforeSend: setHeader 
    }); 
}); 
0

我不知道,如果你的API的信息是正確的,但我認爲你需要做的主要事情是變化的JSON由於musa提及的同一起源政策,而不是json。

下面的JS小提琴「工作」,但請求未被授權在服務器:http://jsfiddle.net/cf8S9/

$(document).ready(function() { 
$('#button').click(function(){ 
$.ajax({ 
     url: 'https://api2.panopta.com/v2/monitoring_node/41', 
     type: 'GET', 
     dataType: 'jsonp', 
     success: function() { alert('hello!'); }, 
     error: function() { console.log(arguments);alert('boo!'); }, 
     beforeSend: setHeader 
    }); 
}); 
function setHeader(xhr) { 
    //extra stuff from REST CLIENT 
    xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY'); 
} }); 
+0

這是不可能的使用JSONP與自定義標題(我的授權密鑰)根據本[問題](HTTP:/ /stackoverflow.com/questions/3073287/set-headers-with-jquery-ajax-and-jsonp),感謝您向我介紹jsfiddle! –