2014-01-23 218 views
-3

我已經找到this question如何將jQuery變量傳遞給php

我的代碼是basicly相同:

<script> 
var x=3; 

$.ajax({ 
    url:'ajax.php', 
    data: {"x":x} 
}); 
</script> 
<? 
echo $_REQUEST['x']; 
?> 

但是看完前面提到的鏈路上的答案後,我仍然不知道,我怎麼能得到它的工作?

請幫忙,謝謝。

+0

你期望發生的? –

+0

什麼是不正確的工作?打開瀏覽器控制檯(F12)並檢查錯誤。確保錯誤報告是在PHP等。 – adeneo

+0

你沒有做任何與PHP返回的數據。你怎麼知道它不工作? – Barmar

回答

0

它可能工作想當然地認爲你的設置是這樣的:

的index.php

<script> 
$(document).ready(function(){ 
    var x=3; 

    $.ajax({ 
     url:'ajax.php', 
     type: 'POST', // should probably set this but I think GET is default 
     data: {"x":x}, 
     dataType: 'html', // we expect html from ajax.php 
     success: function(data){ // listen for a 200 response from server 

      // show the output of ajax.php 
      alert(data); 

      // send it to the <body> 
      $('body').html(data); 

     }, 
     error: function(){ 

      alert('oh snap! we did not get a 200 response, definitely check the network tab for proper debug'); 

     } 
    }); 
}); 
</script> 

<body> 
</body> 

ajax.php

<? 
echo $_REQUEST['x']; 
?> 

發現它們是獨立的文件。

要調試,確保您正在查看index.php,按F12和頭部到網絡選項卡,刷新頁面,找到HTTP調用ajax.php並單擊它

+0

我正試圖在同一頁面上解決它......或者那是不可能的? – user3104757

+0

可能,是的。建議,親愛的宗教圖NO!你爲什麼問?因爲成功的回調會收到整個javascript和'echo $ _REQUEST;'你當然可以試試,但'alert(data)'會讓你清楚爲什麼你不應該這樣做。 – MonkeyZeus

+0

請看看更新,並注意''標籤shenanigans – MonkeyZeus

0

嘗試:

<script> 
var x=3; 

$.ajax({ 
    url:'ajax.php', 
    data: { myx : x }, 
    type: 'post', 
}); 
</script> 
<? 
echo $_POST['myx']; 
?> 
0

你將不得不使用你的Ajax請求GET或POST,否則將無法正常工作。所以,如果你將它張貼到ajax.php,你可以使用變量上ajax.php,不能在同一網頁

+0

因此無法在同一頁上顯示傳遞的變量? – user3104757