从ajax响应返callback用javascript函数后,页面保持刷新
我已经尝试了从Ajax响应返callback用JavaScript函数的大部分答案。 每个答案的工作,但我必须调用alert来显示ajax响应来查看结果(如果不使用函数refreshResults中的alert,有时结果将显示,但立即消失)似乎页面保持清爽。
这是截图。
我已经testing过浏览器可以从服务器上成功接收数据。 问题是如何从浏览器端显示数据。
以下是与从服务器接收数据以及服务器如何返回数据有关的代码。
阿贾克斯
function sendAjaxQuery(url, data) { $.ajax({ type: 'POST', url: url, data: data, success: function (data) { //eval(document.getElementById("refreshResults").innerHTML); refreshResults(data); //$("#firstname").text(data); // alert('success '+data); } }); }
这是我如何发送数据到服务器。
sendAjaxQuery('http://localhost:3000/results.html',JSON.stringify($('form').serializeObject()));
JS
<script type="text/javascript"> function refreshResults(data){ $("#firstname").text(data); alert(data); } </script>
服务器端是nodejs。 (服务器端返回一个string,状态是200)。 http头是
"Content-Type": "text/plain",'Access-Control-Allow-Origin': '*'
这是点击处理程序。
function sendData() { var form = document.getElementById('myform'); sendAjaxQuery('http://localhost:3000/results.html',JSON.stringify($('form').serializeObject())); } var sendButton = document.getElementById('sendButton'); sendButton.onclick = sendData;
这是根据html
<form id="myform"> <input type="text" name="Search" value=""> <button id="sendButton" >Search</button>
sendAjaxQuery
方法的重点是什么?
它只是重新创build$.post
所做的
只是使用
// url and data should be whatever you pass to sendAjaxQuery now $.post(url, data, refreshResults);
每当你想打一个阿贾克斯电话..
更新看到您提交表单的内容,问题可能是您允许表单以正常方式提交( 这会导致页面刷新 )。
您将需要取消启动此操作的button的正常操作。
既然你正在使用jQuery,最好使用它来绑定事件处理程序
更改
var sendButton = document.getElementById('sendButton'); sendButton.onclick = sendData;
至
$('#sendButton').on('click', function(e){ e.preventDefault(); sendData(); });