【问题标题】:Run Javascript script from ajax response从 ajax 响应运行 Javascript 脚本
【发布时间】:2016-09-30 03:27:20
【问题描述】:

我想在 Ajax 响应中调用一个 JS 脚本。它的作用是将document.getElementById 脚本传递给Ajax responseText。

当前代码返回此错误:Uncaught TypeError: Cannot set property 'innerHTML' of null

这是通过 Visual Studio Cordova 完成的。

阿贾克斯:

$("#loginBtn").click(function() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            document.write(this.responseText);
        }
    }
    xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("username=" + username + "&" + "password=" + password);
});

PHP:

if($count == 1){
   echo "document.getElementById('alertBox').innerHTML = 'Login Success!';
        document.getElementById('alertBox').className = 'alert alert-success';
        document.getElementById('alertBox').style.display = 'block';
        setTimeout(function () {
                window.location.href = '../html/dashboard.html';
            }, 1000);
        ";
}else{
       echo "document.getElementById('alertBox').innerHTML = 'Invalid login details'; 
        document.getElementById('alertBox').className = 'alert alert-danger';
        document.getElementById('alertBox').style.display = 'block';
        ";
}

【问题讨论】:

  • 当你访问id为alertBox的元素不在DOM中并尝试设置innerHTML。您是否在 ajax 调用之前将其附加到某处?如果不是,您需要先这样做。
  • 我认为让 PHP 只返回一个成功/失败指示器并让现有的 Ajax JS 测试返回值并使用适当的类显示适当的消息会更容易。另外,鉴于您使用的是 jQuery,为什么要手动编写自己的 Ajax 调用而不是使用 $.ajax()
  • 您需要创建一个脚本元素,然后从响应中添加文本,然后将该元素添加到 DOM
  • 好吧,你可以这样做,但这是一件危险的事情,因为你基本上需要评估它。而且你不应该在页面加载后使用 document.write。
  • 问题是document.write()在初始页面加载后运行时会清除页面中的所有内容......然后你不能使用getElementById......没有更多元素了

标签: javascript php jquery ajax visual-studio-cordova


【解决方案1】:

你可以通过一个小的改动来解决它,你只需要在你的PHP页面中编写的AJAX成功中编写JS代码。在PHP页面中,没有alertBox元素,这就是错误发生的原因。

你的 JS 代码会是这样的:

$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        if(this.responseText=="success"){
        document.getElementById('alertBox').innerHTML = 'Login Success!';
        document.getElementById('alertBox').className = 'alert alert-success';
        document.getElementById('alertBox').style.display = 'block';
        setTimeout(function () {
        window.location.href = '../html/dashboard.html';
        }, 1000);
        }elseif(this.responseText=="error"){
         document.getElementById('alertBox').innerHTML = 'Invalid login details'; 
    document.getElementById('alertBox').className = 'alert alert-danger';
    document.getElementById('alertBox').style.display = 'block'
         }
    }
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
  });

PHP 代码如下:

 if($count == 1){
 echo "success";
 }else{
   echo "error";
  }

【讨论】:

  • 我怎么没想到。非常感谢!
【解决方案2】:

基本上,您会收到该错误,因为您要更改的内容在您查找时不在页面上。

你需要做的是,不要用 PHP 编写 javascript。你从 php 返回类似 int 的东西,然后用它来决定 javascript 的作用。

您在页面上有 html,只需更改其中的内容。

$("#loginBtn").click(function() {
      var username = document.getElementById("username").value;
      var password = document.getElementById("password").value;
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

          var str = this.responseText; //you may need to trim whitespace
          var alert = document.getElementById('alertBox');
          if (str.trim() == 1) {

               alert.innerHTML = 'Login Success!';
               alert.className = 'alert alert-success';
               alert.style.display = 'block';
               setTimeout(function() {
                 window.location.href = '../html/dashboard.html';
               }, 1000);

          } 
          else {

               alert.innerHTML = 'Invalid login details';
               alert.className = 'alert alert-danger';
               alert.style.display = 'block';

          }
        }
        xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send("username=" + username + "&" + "password=" + password);
      });
<div id="alertbox"></div>

PHP 代码:

 if($count == 1){
      echo 1;
}
else{
      echo 0;
}

【讨论】:

  • 在 php 中使用字符串时应该修剪响应...添加额外的空格是臭名昭著的
  • 完成了,不过我从来没有遇到过这个问题。
  • 如果您不需要进行响应比较,通常不是问题
  • 我经常做这种比较。不过也可能与输出缓冲和其他因素有关。
【解决方案3】:

使用下面的 eval

$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        var fun = eval(this.responseText);
    }
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 2014-10-09
    • 2013-10-06
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多