2011-09-20 53 views
0

所以我有一個目錄名爲paste.php一個PHP文件與域example.com(http://www.example.com/ajax/paste.php) PHP文件看起來像一個服務器:阿賈克斯jQuery的請求到另一個域

<?php 
$id=($_GET['create']); 
$paste=($_GET['paste']); 
$toly=($_GET['toly']); 
if($id=='create'){ 
echo "hello";} 
else{ 
echo "world"; 
} ?> 

在另一臺服務器不同域我有一個簡單的HTML文件(www.example /演示/ index.html的) 我想提出一個AJAX調用PHP文件上面沒有運氣 我的jQuery的樣子:

var url="http://www.example.com/ajax/paste.php"; 
s="create=create&paste=hello&toly=this"; 
$.ajax({ 
    type: "GET", 
    xhrFields: { 
     withCredentials: true 
    }, 
    url: url, 
    data: s, 
    success: function(msg){ 
    alert(msg); 
    },error:function (jqXHR){ 
        alert(jqXHR.status.error); 
       } 
}); 

我是什麼d錯了嗎?

編輯:忘記XHR我只是想找回我已經爲響應 字符串有什麼辦法?

+0

看到http://stackoverflow.com/questions/727183/can-jquery-ajax-call-external-webservice –

回答

2

從JavaScript中,您可以在文檔頭部動態創建一個新元素。當你這樣做的時候,瀏覽器可以從你指定的任何域中去請求數據。如果被調用的代碼包含某個函數的執行,那麼該函數將能夠鏈接到您的代碼。下面是例子:

var head = document.getElementsByTagName("head")[0]; 
    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = url; 
    head.appendChild(script); 

您還需要定義你的腳本里面的函數:

function success(abc){ 
     alert('Yey'+abc); 
    } 

腳本形成其他域應該是這樣的:

success('some_data_here'); 

該數據也可以是JSON。當JSON與這樣的函數調用結合使用時,它被稱爲JSONP。

進一步閱讀這裏:

http://en.wikipedia.org/wiki/JSONP