Jquery异步请求数据实例代码
一、jquery向x页面请求数据
前台页面js代码:
代码如下:
$("#button1").bind("click", function () {
$.ajax({
type: "post",
url: "default.aspx",
data: "name=" + $("#text1").val(),
success: function (result) {
alert(result.msg);
}
});
});
代码如下:
<input id="text1" type="text" value='张三'/>
<input id="button1" type="button" value="提交" />
代码如下:
protected void page_load(object sender, eventargs e)
{
if (request["name"]!=null)
{
response.contenttype = "text/json";
response.write("{\"msg\":\""+request["name"]+"\"}");//将数据拼凑为json
response.end();
}
}
代码如下:
$("#button2").bind("click", function () {
$.ajax({
type: "post",
contenttype: "application/json",
url: "webservice.asmx/helloworld",
data: "{name:'" + $("#text1").val() + "'}",
datatype: "json",
success: function (result) {
alert(result.d);
}
});
});
<input id="button2" type="button" value="向webservice提交" />
代码如下:
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.services;
/// <summary>
/// summary description for webservice
/// </summary>
[webservice(namespace = "https://tempuri.org/")]
[webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]
// to allow this web service to be called from script, using asp.net ajax, uncomment the following line.
[system.web.script.services.scriptservice]
public class webservice : system.web.services.webservice {
public webservice () {
//uncomment the following line if using designed components
//initializecomponent();
}
[webmethod]
public string helloworld( string name) {
return "hello world"+name;
}
}
js代码:
代码如下:
$("#button3").bind("click", function () {
$.ajax({
type: "post",
url: "handler.ashx",
data: "name=" + $("#text1").val(),
success: function (result) {
alert(result.msg);
}
});
});
代码如下:
<%@ webhandler language="c#" class="handler" %>
using system;
using system.web;
public class handler : ihttphandler {
public void processrequest (httpcontext context) {
context.response.contenttype = "text/json";
context.response.write("{\"msg\":\"hello world"+context.request["name"]+"来自handler.ashx\"}");
context.response.end();
}
public bool isreusable {
get {
return false;
}
}
}
下一篇: 如何将模拟人生3mod安装到游戏中