php – 使用xml将javascript变量发布到服务器
我在这里的第一篇文章我是
Java / AJAX的新手,但我有一些
PHP经验.我试图将html表单数据传递给php文件进行处理.目标是让php脚本处理表单数据并返回true / false标志.我正在尝试AJAX,因为我不想要屏幕刷新.根据php脚本的响应,弹出窗口将覆盖现有屏幕,并向用户显示信息.
我的HTML表单代码是: – <form name="screen3" method="post" action="" id="scr3" /> <input type="image" src="images/proceed.jpg" alt="Proceed" id="proceed1" name="submit" value="Send" /> </form> 我使用javascript从表单重定向了提交按钮: – <script type="text/javascript"> $(document).ready(function() { $('#proceed1').click(function(e) { e.preventDefault(); x=validateScreen3(); if (x) {getFormData();} }) }); </script> 到目前为止一切顺利,validateScreen3()被调用并验证用户条目(不会让你厌烦脚本).调用getFormData但问题出在哪里: – function getFormData() { var xmlhttp; var emailAddress = document.getElementById("emailaddress").value; var entryCode = document.getElementById("entrycode").value; var acceptance = document.getElementById("acceptance").value; var Sel = document.getElementById("sel").value; xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","test1.php",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("emailaddress="+emailAddress); } 我已经确认变量数据已传递给函数ok,但上面引用的test1.php脚本似乎正在被调用/执行.这是test1.php文件: – <?php $here = $_POST['emailaddress']; echo '</div></div>'; if (!empty($here)) { echo '<div style="position:absolute; top:100px; left:300px; width:400px; height:200px; background-color:#CCC; color:#000; z-index:50;">'; echo 'got the variable '.$here; echo '</div>'; } else { echo '<div style="position:absolute; top:100px; left:300px; width:400px; height:200px; background-color:#CCC; color:#000; z-index:50;">'; echo 'DIDNT GET the variable '.$here; echo '</div>'; } ?> 这些div都没有显示出来,并且从我能想到的每个测试中都可以看出,文件根本就没有被调用.任何想法或建议将不胜感激. 解决方法
您需要为XMLHttpRequest的onreadystatechange事件添加事件处理程序.当PHP发送响应时,将触发此事件:
xmlhttp.onreadystatechange = function(response) { if (this.readyState===4 && this.status===200) {//readyState 4 means request is finished document.body.innerHTML += response;//since it's an HTML response... } }; 但是既然你正在使用jQ,你不必担心所有这些标题……只需check 在某些时候,你可能想要抛弃jQ,因为你必须支持旧的浏览器(IE <9,甚至IE< 8).在那种情况下this might prove helpful 澄清: var xhr =new XMLHttpRequest(); xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) {//response is xhr property in vanilla JS document.body.innerHTML += this.responseText; } if (this.readyState === 4 && this.status !== 200) {//error in request console.log(this);//<-- check your console document.body.innerHTML += '<h1>Http error: ' + this.status; } }; xhr.open("POST",true); xht.send("emailaddress="+emailAddress); 这应该工作得很好.如果,由于某种原因,它没有,尝试使用jQuery,如下所示: $.ajax({ url: 'test1.php',type: 'POST',data: {emailaddress: $('#emailaddress').val()},success: function(response) { document.body.innerHTML += response; } }); 如果这对您不起作用,那么您的网址可能是错误的,或者运行您的PHP脚本的服务器位于另一个域上,或者您必须发布一个后续问题.但希望这会有所帮助 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |