2015-06-29 48 views
1

我在ajax中有以下代碼。我將兩個參數$job_idq傳遞到了一個名爲interview.php的頁面,但是。但是,該頁面給我的警告是$job_id未定義。我不知道如何使用AJAX POST或GET多個變量。從Ajax向PHP傳遞數據

我的AJAX文件是:

<script> 
function showSuccess ($getid,str) { 
    var job_id= $getid; 
var resp; 
if (window.XMLHttpRequest) { 
    resp = new XMLHttpRequest(); 
    xmlhttp = new XMLHttpRequest(); 
} else if (window.ActiveXObject) { 
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
} 
var data = "job_id="+job_id 
    xmlhttp.open("POST", 
     "interview.php?q="+str); 
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");     
    xmlhttp.send(data); 
    xmlhttp.onreadystatechange = 
    function display_data() { 
    if (xmlhttp.readyState == 4) { 
     if (xmlhttp.status == 200) { 
     document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 

} 
    } else { 
     alert('Request not successful.'); 
     } 
    } 
    } 


</script> 

interview.php:

<?php 
$q = intval($_POST['q']); 
?> 
<?php 

$getid = $_POST['job_id'];?> 

<?php 
include('includes/conn.php'); 

$row="SELECT idNo,id,name,jobTitle,SUM(points) AS total FROM shortlist WHERE job='$getid' GROUP BY id ORDER BY total DESC LIMIT $q"; 
$query=mysqli_query($conn,$row) or die(mysqli_error($conn)); 

while($row=mysqli_fetch_array($query)) 
{ 
    echo $row['name']; 
} 

mysqli_close($conn); 
?> 
+0

'var job_id = $ getid;'是否有效? –

+0

運行的腳本是'else alert('請求不成功'); }'在警告框中單擊確定後,我收到一條警告:q未定義索引 – Colo

+0

請嘗試....數據:{para1:value1,para2:value2} – user1844933

回答

0

如果你不理解JavaScript和Ajax,只是儘量用一些簡單的像jQuery。

實際上你只給PHP腳本一個變量,這就是你得到這個錯誤的原因。嘗試改變這一點:

xmlhttp.open("POST", "interview.php?q="+str); 

xmlhttp.open("POST", "interview.php?q="+str+"&job_id="+job_id); 
+0

另外如果你想用純js來閱讀並學習這個http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp – SkyFox

0

更改data這個var data = "job_id="+job_id+"&q"+str
Undefined index: q是因爲您正在使用post方法獲取數據,並且您使用get方法發送數據,這就是爲什麼您會收到錯誤。
請嘗試下面的代碼。

xmlhttp.open("POST","interview.php"); 
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");     
xmlhttp.send(data); 
+0

並且介意這個'var job_id = $ getid;'不會給任何值賦值你的'job_id'。 :) –