【问题标题】:confusion about basic AJAX code对基本 AJAX 代码的困惑
【发布时间】:2013-05-02 15:20:07
【问题描述】:
<script>
    try {
        function xmldo() {
            var xmlhttp;
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("para").innerHTML = xmlhttp.responseText;
                }
            }
            var URL = "http:\\127.0.0.1\ajax.php";
            xmlhttp.open("GET", URL, true);
            xmlhttp.send();
        }
    } catch (err) {
        document.write(err.message);
    }
</script>
<p id="para">Hey message will change</p>
<br>
<button type="button" onclick="xmldo()">Click me</button>

这是我的代码网页,我想通过我的另一个 php 文件 ajax.php 中的响应来更改#para.innerHTML 的内容

<?php
$response="hey is text changed";
echo $response;
?>

我正在使用 wamp,所以我将 ajax.php 放在我的 www 文件夹中,并将服务器上文件的位置设置为 127.0.0.1/ajax.php [URL] 但我按下按钮时 para 占位符处的文本不是改变。 我是 AJAX 的新手,所以在某些方面必须遗漏。请帮帮我。

【问题讨论】:

  • 我建议你使用 jQuery 之类的库来执行 AJAX 请求 - 它的主要好处是它需要更少的代码并且可以在各种浏览器中使用。
  • 您是否尝试将"http:\\127.0.0.1\ajax.php" 更改为"http://127.0.0.1/ajax.php"
  • @ajtrichards 我现在对 Jquery 一无所知,但非常感谢您的宝贵建议。

标签: php javascript xml ajax wamp


【解决方案1】:

更改 URL 中的斜杠。

你有:http:\\127.0.0.1\ajax.php,但正确的方法是:http://127.0.0.1/ajax.php

我还建议使用 jQuery 来执行 AJAX 请求 - 它更简单,并且您编写的代码更少!

我在下面添加了一个用 jQuery 编写的示例:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

    $("#button_id").click(function(){

        $.ajax({
            url: 'http://127.0.0.1/ajax.php',
            cache: false,
            type: 'GET',
            dataType: 'HTML',
            error: function (e){
                console.log(e);
            },
            success: function (response){
                $("#para").empty().append(response);
            }
        });

    });

});
</script>

<p id="para">Hey message will change</p><br>
<button type="button" id="button_id">Click me</button> 

【讨论】:

  • 显然成功:在最新的 jQuery 中已弃用(我实际上是前几天才发现的!)它完成了:现在
  • 哦!我不知道那件事。谢谢@Dave
  • 请解决我的问题,并为我提供正确的 javascript 代码,因为目前我只知道它。而且 url 斜杠不会对结果产生影响,但会改变它们
  • @Dave success 选项 已弃用。 .success() 方法**/**回调 是。你可以使用$.ajax({}).success(function () {});,但现在你使用$.ajax({}).done(function () {})
  • 弃用通知:jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调自 jQuery 1.8 起已弃用。要为最终删除准备代码,请改用 jqXHR.done()、jqXHR.fail() 和 jqXHR.always()。
猜你喜欢
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-12
  • 2012-10-05
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多