欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Jquery异步请求数据实例代码

程序员文章站 2023-11-14 11:07:22
一、jquery向x页面请求数据 前台页面js代码: 代码如下: $("#button1").bind("click", function () { $.aj...

一、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="提交" />

后台cs代码:

代码如下:

protected void page_load(object sender, eventargs e)
{
if (request["name"]!=null)
{
response.contenttype = "text/json";
response.write("{\"msg\":\""+request["name"]+"\"}");//将数据拼凑为json
response.end();
}
}

二、jquery向webservice页面请求数据

代码如下:

$("#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提交" />

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;
}
}

三、jquery向ashx请求数据和向页面相同
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;
}
}
}