duangu4980 2011-04-28 19:31
浏览 36
已采纳

AJAX调用不执行JavaScript函数。 为什么? 变通?

I'm *POST*ing to a PHP login script via an AJAX call. Upon success, I need to call a JavaScript function loggedIn(). I tried having it print ...

<script type="text/javascript">loggedIn();</script>

... as the .innerHTML of a div, as well as trying an onload="" event on the div tag. Neither method allowed me to call the JavaScript function. I can print a letter inside the div and execute it on the onclick="" event, but the whole thing I'm trying to get away from is actually having to click anything. Bascially, I want a header("...") redirect (which also wouldn't work).

First, can someone explain what is actually happening? My bet is on the asynchronous nature of AJAX. Secondly, does anyone know a work around I might employ go about refreshing the page upon success?

Thanks as always, Z@K!

  • 写回答

4条回答 默认 最新

  • dongqie2355 2011-05-11 15:02
    关注
    // Create a callback handler
    xmlHttp.onreadystatechange = function () {
        // readyState == 4 | The request is complete
        // status == 200 | Request completed successfully.The page is found and displayed.
        if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) {
            if (xmlHttp.responseText == "SUCCESS") {
                document.location.href = redirect_url;
            } else {
                var elemObj = document.getElementById(div_id);
                elemObj.innerHTML = xmlHttp.responseText;
            }
        }
    }
    

    In my normal callback handler I added...

            if (xmlHttp.responseText == "SUCCESS") {
                document.location.href = redirect_url;
            }
    

    Since HTML is a string, and "SUCCESS" is a string I didn't really have to do anything different, except check the results of the login action for "SUCCESS". Then use document.location.href to redirect the page to the appropriate URL.

    This works perfect for my application. Thank you everyone for your input!

    ~Z@K!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100