【发布时间】:2017-03-29 11:11:13
【问题描述】:
感谢大家提供这么多热忱的支持
今天我遇到了一些关于 Json 字符串的问题,我在 json 中返回了一些值并尝试在 Ajax Success 中检索,但我无法获取变量的值
//Return the value from registration.aspx.cs page
[WebMethod]
public static string verifyAadhar(string aadharNum)
{
HttpContext context = HttpContext.Current;
//try
//{
context.Session["aadharNum"] = aadharNum;
string url = "http://localhost:3787/api/login/login?aadharID=908765478921";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "POST";
/*Optional*/
request.KeepAlive = true;
request.AllowAutoRedirect = false;
request.Accept = "application/json, text/javascript, */*; q=0.01";
request.ContentType = "application/json; charset=utf-8"; //"application/x-www-form-urlencoded";
///*Optional*/
string userId = "abc";
string Passwd = "123456";
string RequestLink = context.Request.Url.Authority;
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("" + userId + ":" + Passwd + "")));
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
//?aadharID = 908765478921
string json = "{\"aadharID\":\"" + 908765478921 + "\"" + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
//try
//{
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
dynamic jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
response.Close();
sr.Close();
return new JavaScriptSerializer().Serialize(new { jsonObject });
//}
//catch (Exception ex)
//{
// return ex.Message.ToString();
//}
}
//Receiving data here in ajax success
var verfAadhar = '{"aadharNum":"' + aadharNum + '"}';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:28331/register/registration.aspx/verifyAadhar",
data: verfAadhar,
datatype: 'json',
async: false,
success: function (data) {
var objData = jQuery.parseJSON(data);
$("#fname").val(objData[4]);
},
error: function ()
{ console.log('Check your credentials'); }
});
请告诉我如何才能获得所有成功数据,例如 [name, fname, dob, gen, mob。
【问题讨论】:
-
请提供“verifyAadhar”方法的完整c#代码
-
首先做一个
console.log(objData)并检查你的对象。然后您可以使用点符号访问其属性,例如objData.name。请注意,您还可以使用数组表示法访问其属性,但使用属性的名称,而不是索引。例如:objData["name"]. -
旁注:$.parseJSON() 在 jquery 3.0 中被贬低了。所以你可能想使用 JSON.parse()。 api.jquery.com/jquery.parsejson
-
您能否提供一些json的示例值,以便我们提供更好的答案?
-
使用成功:function (data) { $("#fname").val(data.fname]); },
标签: c# jquery asp.net json ajax