通过Ajax获取变量

Fetching variables through Ajax

本文关键字:变量 获取 Ajax 通过      更新时间:2023-09-26

我在通过ajax获取表时遇到问题。这是我的ajax函数:

function search() {
    var JobFunction_Id=document.getElementById("JobFunction_Id").value;
    var JobFamily_Id=document.getElementById("JobFamily_Id").value;
    var flag=0;
    var newreq=createRequest();
    if(JobFunction_Id!='' && JobFamily_Id!='') { flag=1; }    
    if(flag==1) {    
        var url=("Talent_S_New.php?JobFunction_Id="+JobFunction_Id+"&      JobFamily_Id="+JobFamily_Id);
        newreq.onreadystatechange=function() {
              alert('hi');
              if(newreq.readyState==4 && newreq.status==200) {
                   if(newreq.responseText!='') {
                       document.getElementById("display_result").innerHTML  =newreq.responseText; }
                    //else {    
                    // document.getElementById("display_result").innerHTML  =newreq.responseText;                     
                    //}
              }
        }
        newreq.open("GET",url,true);
        newreq.send();
    }
}​

我正在尝试从这个页面获取带有表信息的输出变量。

echo('<table style="border:1px solid red" >');
echo('<th>');
echo('First Name');
echo('</th>');
echo('<th>');
echo('Last Name');
echo('</th>');
echo('<tr>');
echo('<td style="border:1px solid red">');
foreach($Allemp as $key=>$value) {
   if (array_key_exists('Error', $Allemp))
   {    echo($value);   }
   else
   {    echo($value["Emp_FirstName"]);  }
   //echo('</td>');
   //echo('<td style="border:1px solid red">');
   if (array_key_exists('Error', $Allemp))
   {    echo($value);   }
   else
   {    echo($value["Emp_LastName"]);   }
}
echo('</td>');
echo('</tr>');
echo('</table>');

没有ajax,上面的代码就可以正常工作。可以观察到alert('hi')。如果我发出警报,它将进入if(newreq.readyState==4 && newreq.status==200)循环,结果将显示一秒钟,然后再次失效。我认为它进入了foreach循环,因为它显示了5次警报,并显示了一秒钟的结果,然后消失了。有什么办法解决这个问题吗?

由于您将其标记为jQuery,我确信其中大部分可以更改为接近的内容

var url=("Talent_S_New.php?Function_Id="+JobFunction_Id+"&JobFamily_Id="+JobFamily_Id);
$.ajax(url, {
  type: "GET",
  success: function(data, status) {
    alert("success!");
    $("#display_result").html(data); // Incoming data placed in 'display_result'
  },
  error: function(jqXHR, textStatus){
    alert("error..");
  }
});

我不知道这是否能解决你的问题。但是您将其标记为jQuery,并且我在您的代码中没有看到一个jQuery调用。

为什么不使用jQuery AJAX?

这里有一个例子:

$.ajax({
  type: "GET",
  url:'Talent_S_New.php',
  data:$('form').serialize,
  complete: function() { alert('hi'); }
  success: function(data) {
      $('#display_result').html(data.responseText);
  } 
});