download12749 2012-06-03 04:03
浏览 38
已采纳

如何使用AJAX将信息发送到PHP脚本?

I cannot get my simple ajax script to run. The code should be pretty simple. The ajax script is:

<html>

<head><title>Testing ajax</title>

    <script type="text/javascript">

        function ajax() {

            var xmlhttp;

            var fname=document.getElementById("fname").value;

            if(window.XMLHttpRequest) {
                xmlhttp=new XMLHttpRequest();
            } else {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.onreadystatechange=function() {

                if (xmlhttp.readyState==4 && xmlhttp.status==200) {

                    document.getElementById("output").innerHTML=xmlhttp.responseText;

                }

            }

            xmlhttp.open("GET","ajax.php?fname="+fname,true);
            xmlhttp.send();

        }

    </script>

</head>

<body>


    <form>

        <input type="text" id="fname">

        <input type="text" id="lname">

        <input type="submit" id="submit" onclick="ajax()">


    </form>


    <div id="output"></div>


</body>

And the php script is:

<?php

$fname=$_GET['fname'];

echo "<p>Hello ".$fname."</p>";

?>

I have also tried:

xmlhttp.open("POST","ajax.php",true);
xmlhttp.setRequestHeader("Content-type","application/pass-data");
xmlhttp.send("fname="+fname);

I can't get neither post not get method to send data. Am I not seeing something simple?

  • 写回答

2条回答 默认 最新

  • douao1926 2012-06-03 04:47
    关注

    The reason it is not working is due to the fact that you have your inputs inside of <form> tags. After removing the form tags, when I tried your code with the <input type="submit" /> control changed to

    <input type="button" onClick="ajax()" value="Submit" />
    

    it worked like a charm. I suspect that form behaviour is handled differently due to certain benefits when submitting, security concerns, and such.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了