为什么这个Java Script POST无法工作?

时间:2015-05-08 21:24:01

标签: javascript c# ajax asp-classic

<script language="javascript">
 function storemarker() {
     var txtTitle = document.getElementById('txtTitle').value;

     var sendInfo = { txtTitle: txtTitle

     };

     var req;
     if (window.XMLHttpRequest) {
         req = new XMLHttpRequest();
     }
     else {
         req = new ActiveXObject("Microsoft.XMLHTTP"); // IE
     }
     req.onreadystatechange = function () {
         if (req.readyState == 4 && req.status == 200) {
             var mydata = JSON.parse(req.responseText);
         }
     }
     req.open("POST", "Home.aspx/ButtonClick", true);
     req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     req.send("txtTitle=" + txtTitle );
 }

<input type="submit" id="button" class="buttom" value="Add Road" onclick="storemarker()"/> 

[WebMethod]
    public static string ButtonClick(string txtTitle)
    {
        //return title;
        return "alert('The Button was Clicked');";
    }

我试图将此作为一个小例子来实现。我刚刚查看了我无法看到错误的代码。

任何人都可以告诉我这段代码有什么问题吗?感谢

1 个答案:

答案 0 :(得分:2)

您必须取消提交按钮的默认行为,即提交表单,或使用普通按钮而不是提交按钮。

现在,您的代码确实向服务器发送请求,但随后也提交了表单,因此页面重新加载&#34;。

其中一种可行:

<input type="submit" id="button" class="buttom" value="Add Road" onclick="storemarker(); return false;"/>

或者:

<button type="button" id="button" class="buttom" onclick="storemarker()">Add Road</button>