dr897777 2013-05-02 15:20
浏览 35

关于基本AJAX代码的混淆

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

This is my code webpage I want to change the content of #para.innerHTML by the respnse in my another php file ajax.php

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

I am using wamp so i placed my ajax.php in my www folder and set the location of file on server as 127.0.0.1/ajax.php [URL] but i on pressing the button the text at para placeholder is not getting changed. I am new to AJAX so must be missing on some points. Plz help me with them.

  • 写回答

1条回答 默认 最新

  • douhuan1901 2013-05-02 15:22
    关注

    Change the slashes in your URL.

    You have: http:\\127.0.0.1\ajax.php but the correct way is: http://127.0.0.1/ajax.php

    I would also suggest using jQuery to perform AJAX requests - it's much simpler and you write less code!

    I've added an example below written in 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> 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用