jsp Ajax无法正常工作
我试图使用一个简单的ajax函数。早期的方式是我的工作perfeclty但今天它不工作。没有工作意味着它甚至没有打开警报框。请看下面的代码
这是javascript
var reqObj=null; function send(){ var number; var msg; msg=document.getElementById("body").value; number=document.getElementById("number").value; alert(number); if(window.XMLHttpRequest){ reqObj=new XMLHttpRequest(); }else { reqObj=new ActiveXObject("Microsoft.XMLHTTP"); } reqObj.onreadystatechange=sukant; reqObj.open("POST","./messageSending.jsp?toNumber=" + number + "&body=" + body ,true); reqObj.send(null); } function sukant(){ if(reqObj.readyState==4 && request.status == 200){ alert(reqObj.responseText); }}
这是我调用ajax的HTML部分
这是messageSending.jsp
任何身体可以告诉我我在哪里做错了吗?
这是我的完整代码
Twilio Messages (Send message Example) $(document).ready(function(){ $('#openAlert').click(function(){ alert("hi"); var number = $('#number').val(); // If its a text input could use .text() var msg = $('#body').val(); //If its a text input could use .text() $.ajax( { type: "POST", url: "messageSending.jsp", //Your full URL goes here data: { toNumber: number, body: msg} success: function(data, textStatus, jqXHR){ alert(data); }, error: function(jqXHR, textStatus, errorThrown){ alert("error"); } }); }); }); Twilio Messages (Send message Example)
Successful
Message sent successfully
根据您的评论,我只能扣除您的表单实际上是在执行常规POST
而不是ajax调用,这使您很难调试问题。
使用
仍会发布和刷新页面,即使操作是哈希。 相反,您应该覆盖表单的onsubmit
事件以返回false。 这可以做到
- 内联:
- 在javascript:
document.getElementById('myForm').onsubmit = function(){return false;};
- 或者使用jQuery:
$("#myForm").on("submit", function() { return false; });
我不熟悉jsp,但以下内容应该有效
jQuery ajax:
$(document).ready(function(){ $('#openAlert').click(function(){ var number = $('#number').val(); // If its a text input could use .text() var msg = $('#body').val(); //If its a text input could use .text() $.ajax({ type: "POST", url: "messageSending.jsp", //**Your full URL goes here** data: { toNumber: number, msg: msg}, success: function(data, textStatus, jqXHR){ alert(data); }, error: function(jqXHR, textStatus, errorThrown){ alert(errorThrown); } }); }); });
HTML:
不要忘记在页面中包含jQuery
编辑检查此FIDDLE 。 它会引发错误的exception,即url不应该,但是当你输入有效的URL时它应该有效