2015-10-06 49 views
0

我有一個ajax問題。我正在做跨域,即我在另一個域上提交表單。跨域阿賈克斯。如何檢查

這裏是我的js代碼:

$.ajax({ 
    url: $(this).attr('action'), 
    type: $(this).attr('method'), 
    data: $(this).serialize(), 
    dataType: 'json' 
}) 
.done(function(data) { 
    console.log('what'); 
}) 
; 

,並在PHP我返回這個字符串:

$response = "Hmmm... Please contact the webmaster at [email protected] as it seems that there is a problem with submitting this form. Error x02"; 
echo json_encode(['response' => $response]); 

我也從我的搜索明白,我應該在我的dataType使用JSONP而不是JSON的,但與jsonp我甚至不能提交我的表格。

當我用json提交表單時,數據被正確插入到我的數據庫中,但我無法得到任何響應。我嘗試.success而不是.done,但也不起作用。

我的第一個問題,我可以用json與域進行跨域嗎?

如果我需要使用jsonp,我該如何在瀏覽器中檢查一切是否正確,以及如何修改我的響應,因爲現在如果使用jsonp我在控制檯中出現錯誤是因爲' :'將價值與關鍵字分開。

感謝您的幫助

+0

可以CORS使其他域....請參見http://計算器.com/a/9866124/1175966 – charlietfl

回答

0

你以這樣的方式還設置了頭在你的PHP,它可以讓你接受來自其他領域也請求。

<?php 

    header('Access-Control-Allow-Origin: *'); 
    header('Access-Control-Allow-Methods: GET, POST'); 
    header("Access-Control-Allow-Headers: X-Requested-With"); 
    $response = "Hmmm... Please contact the webmaster at [email protected] as it seems that there is a problem with submitting this form. Error x02"; 
    echo json_encode(['response' => $response]); 

?> 

詳細解釋在這裏給出:
(1)CORS with php headers
(2)http://www.w3.org/TR/cors/
(3)https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

+0

謝謝,正試圖弄清楚如何使它在js中工作,同時在PHP文件中添加標題確實解決了問題。 –