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条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决