【发布时间】:2016-02-22 10:11:21
【问题描述】:
我有这个 ajax 函数:
$.ajax({
url: "http://localhost:56472/WebSite2/Service.asmx/Area",
method:"post",
data: {
l: "custom value",
b: "custom value",
}
success: function (data) {
console.log(data.length);
var xmlDoc = $.parseXML(data);
var jXml = $(xmlDoc);
var value = jXml.find("int").text();
$("#result").text(value);
},
failure: function (err) {
console.log("could not call the service : " + err);
}
});
我想在这个 html 中使用它来显示结果:
<html>
<head>
<title>WebService Call using HTTP POST</title>
<body>
<form action="http://localhost:56472/WebSite2/Service.asmx/Area" method="POST">
<input name="l">
<input name="b">
<input type="submit" value="Click for Area">
</form>
</body>
</head>
</html>
有人能告诉我如何用这个表单调用这个 ajax 吗?以及完整的 html 会是什么样子?
非常感谢 :)!
编辑:
<html>
<head>
<title>WebService Call using HTTP POST</title>
<body>
<script>
$(function () {
function clickme() {
$.ajax({
url: "http://localhost:56472/WebSite2/Service.asmx/Area",
method: "post",
data: {
l: "custom value",
b: "custom value",
},
success: function (data) {
console.log(data.length);
var xmlDoc = $.parseXML(data);
var jXml = $(xmlDoc);
var value = jXml.find("int").text();
$("#result").text(value);
},
failure: function (err) {
console.log("could not call the service : " + err);
}
});
};
$("button").on("click", clickme)
});
</script>
<form method="POST">
<input name="l">
<input name="b">
<button type="button" onclick="clickme()">Click for Area</button>
</form>
<h1 id="result"></h1>
</body>
</head>
</html>
【问题讨论】:
-
从表单中删除操作,创建一个按钮并绑定点击事件来调用您的 ajax 代码。这方面有很多示例。
-
@Jules 好的,你能检查一下我编辑的代码吗?我应该在 onclick 方法中写什么? ajax 没有名称或其他东西,所以我可以调用它?
-
$(function(){function clickme(){your ajax code here}; $('button').on('click', clickme }); 建议,阅读jquery文档了解代码。
-
@Jules 你能检查一下编辑后的代码吗?我照你说的做了,但什么也没发生,不知道是不是做错了什么?
-
您的代码格式不正确(部分是我的错)。我把更正的副本放在这里jsfiddle.net/u7f1npxq