2017-08-29 58 views
0

我使用以下函数对发生onChange-事件时从MySQL数据库检索数据的PHP进行ajax调用。 PHP的结果是包含一些数据的JavaScript函数。从ajax运行javascript

基本上,我将所有的代码复制到W3Schools的xmlhttp.send()。 然后,面对在我的页面上调用JavaScript的问题,我添加了与$.getScript(...)的部分。

它的工作原理,但我有一种感觉,拨打getRun.php?run=...两次不能是最好的方式。

function getRun(str) { 
if (str == "") { 
    document.getElementById("txtHint").innerHTML = ""; 
    return; 
} else { 
    if (window.XMLHttpRequest) { 
     // code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp = new XMLHttpRequest(); 
    } else { 
     // code for IE6, IE5 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      document.getElementById("txtHint").innerHTML = this.responseText; 
     } 
    }; 
    xmlhttp.open("GET","getRun.php?run="+str,true); 
    xmlhttp.send(); 
    $.getScript("getRun.php?run="+str, function() { 
     setTimeout(); 
    }); 
} 

}

你有什么会是一个更好的办法任何提示?

+0

而不是通过PHP在你的Ajax请求返回整个JavaScript函数,为什么不包括在你的脚本功能,运行Ajax请求,只返回你所需要的数据并传递给函数? – Milanzor

回答

0

为了进一步说明对你的问题我的评论:

  1. 定义你想从你的Ajax结果运行
  2. 启动您的Ajax请求到PHP后台的功能。
  3. PHP后端返回某个结果,不管是string还是JSON,都由您决定。
  4. 在Ajax成功(或错误或完全偶数)回调中调用该函数。

例如,

function getDataFromBackend(){ 

    // Your Ajax request 
    // Seeing as you tried to use $.getScript, you might be using jQuery, so an example with jQuery 
    $.ajax({ 
     method: 'POST', 
     url: 'yoururl.php', 
     data: {}, // You can put whatever data you wanna send in this object 
     success: runMeWithData // The success callback runs the function when the Ajax request comes back without errors. 
    }); 

} 

function runMeWithData(dataFromAjax){ 
    console.log(dataFromAjax); // Show the output of your backend in the Console 
} 
+0

这听起来很合理,谢谢。只需要弄清确切的代码,但是你引导了我一个好方法。 – heckerf