【问题标题】:Change Javascript src Depending On PHP Output根据 PHP 输出更改 Javascript src
【发布时间】:2015-04-20 08:21:49
【问题描述】:

您如何更改 foo.html 中的 Javascript src 以响应通过 AJAX 从 cond1.php 创建的输出?例如,如果 cond1.php 回显 1 则 src="something.js"

我想知道这一点,因为在我的实际项目中,我将使用 Google Books API,并且我需要根据 PHP 文件的输出使用不同的 src。

foo.html

<!DOCTYPE html>
<html>  
  <body>
	<!-- Input -->
    <div class="form">
      <form onsubmit="makeRequest(); return false">
        <input type="text" id="inputText" name="inputText">
        <input type="submit">
      </form>
    </div>
	
    <br>
    
    <!-- Output -->
    <div class="txtBox">
      <textarea  id="txtBox">
      </textarea>
    </div>
    
    <!-- AJAX to create output using cond1.php file-->
    <script>
        function makeRequest() {
            httpRequest = new XMLHttpRequest();            
            httpRequest.onreadystatechange = function() {               
                document.getElementById("txtBox").innerHTML = httpRequest.responseText;
            };
            httpRequest.open("POST", "cond1.php", true);
            httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            httpRequest.send("inputText=" + document.getElementById("inputText").value);
        }

    </script>
    <script src=""></script>
  </body>
</html>

cond1.php

<?php
$input = $_POST["inputText"];

if ($input == "") {
    echo "0";
} else {
    echo "1";
}
?>

【问题讨论】:

    标签: javascript php html ajax xml


    【解决方案1】:

    查看 jQuery 的 getScript 方法,这将允许您通过 ajax 动态和有条件地加载您的 JavaScript。

    【讨论】:

      【解决方案2】:

      您可以在 DOM 中动态创建脚本标签,并使用 ajax 响应将其设置为 src。

      httpRequest.onreadystatechange = function() {               
        document.getElementById("txtBox").innerHTML = httpRequest.responseText;
        var scriptElem = document.createElement("script");
        scriptElem.src = httpRequest.responseText;
        document.getElementsByTagName("head")[0].appendChild(scriptElem)
      };
      

      检查这是否适合您。

      【讨论】:

      • 嗨 Sandeeproop,我试过了。首先我加载了页面,然后检查了源。 src="" 符合预期。然后我在输入中输入“asdf”并按下提交。第二次查看源代码后,我注意到它仍然是 src=""。我猜它是为了显示 src="1"。我是不是做错了什么?
      • 在你的代码中添加 console.log(httpRequest.responseText) 并检查你得到了什么值。
      • 我在httpRequest = new XMLHttpRequest() 之后输入了console.log(httpRequest.responseText)。我输入了asdf,然后提交了。以下是 Chrome 的 Javascript 控制台中显示的内容。首先有一个空行,末尾有:foo.html:24。在下一行,有一个红色的 x,后跟一个指向右侧的三角形,然后是文本 GET http://localhost/1,然后是 foo.html:30
      • 这意味着您获得了正确的路径,现在您可以检查您的 html 标签并检查其中包含 src= "localhost/1" 的新脚本标签。
      • 那么,如何检查 src 是否已更改?也许它正在工作,但我没有以正确的方式看待它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 2011-02-05
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多