weixin_33682719 2017-08-29 14:06
浏览 37

从ajax运行javascript

I use the following function to make an ajax call to a PHP that retrieves data from a MySQL database whenever an onChange-Event occurs. The result of the PHP is a JavaScript function including some data.

Basically, I copied all the code down to xmlhttp.send() from W3Schools. Then, facing the problem of calling the JavaScript on my page, I added the part with $.getScript(...).

It works, but I have a feeling that calling getRun.php?run=... twice cannot be the best way.

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();
    });
}

}

Do you have any hints on what would be a better way?

  • 写回答

1条回答 默认 最新

  • weixin_33736832 2017-08-29 14:22
    关注

    To further explain my comment on your question:

    1. Define the function you want to run from your Ajax result
    2. Launch your Ajax request to your PHP backend.
    3. The PHP backend returns a certain result, be it a string or some JSON, up to you.
    4. Call the function in the Ajax success (or error, or complete even) callback.

    E.g.

    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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作