2016-09-21 88 views
-1

我已經成功創建了幾個AJAX調用,但不知何故,以下簡單的AJAX測試不起作用。我有兩個變量,這些變量是通過輸入表單設置的(這個工作)。我們稱這些變量爲input_1和input_2。我想將這些輸入傳遞給一個php文件,php文件處理它並返回一些東西。最後,響應被設置在JS變量中。現在我將響應放在DOM元素中,以查看AJAX調用是否成功。不幸的是,它不是。未處理AJAX響應

我的代碼:

<html> 
<head> 
</head> 
<body> 

<script type="text/javascript"> 

var input_1 = 'abc'; // this is input of the form 
var input_2 = 'def'; // this in input of the form 

function generate_content(x,y) 
{ 

$.ajax({ 
      url: "create_response.php", 
      type:"get", 
      data:{firstvar:x, secondvar:y} 
     }).success(function(response){ 
      document.getElementById("temp-id").innerHTML=response; 
     });   

} 

generate_content(input_1, input_2); 

</script> 

<p id="temp-id"></p> 

</body> 

</html> 

而且PHP文件create_response.php:

<?php 

$var1=$_GET['firstvar']; 
$var2=$_GET['secondvar']; 

echo $var1; 

?> 

所以,我希望顯示在被稱爲P標籤INPUT_1(= 'ABC')'臨時ID」,因爲

  • INPUT_1被髮送到create_response.php作爲firstvar
  • create_response.php得到firstvar並將其設置爲$ VAR1
  • $ VAR1相呼應,這是成功的功能AJAX
  • 成功函數的響應顯示在P標籤「臨時ID」

但事實並非如此。

有什麼想法/建議嗎?

+0

什麼顯示?如果什麼都沒有,那麼可能解析或語法錯誤 –

+1

是你顯示的文件的整個內容的HTML/JS代碼?它看起來像你試圖使用jQuery,但沒有包括jQuery。 –

+0

您的代碼不符合[JS代碼風格標準。](http://www.w3schools.com/js/js_conventions.asp) 請養成遵循這些風格的習慣。 – Shadetheartist

回答

1

AFAIK沒有對$.deferred沒有success方法,也許你應該試試.then.done

function generate_content(x,y) { 
    $.ajax({ 
     url: "create_response.php", 
     type:"get", 
     data:{firstvar:x, secondvar:y} 
    }).then(function(response){ 
     document.getElementById("temp-id").innerHTML=response; 
    });   
} 
0

您可以添加功能上設置的success屬性對象,而不是使用像Ajax調用內,就像你現在一樣。

$.ajax({ 
    url: "create_response.php", 
    type:"get", 
    data:{firstvar:x, secondvar:y}, 
    success: function(response){ 
     document.getElementById("temp-id").innerHTML=response; 
    } 
});