开发者

ajax not running after var data = json_parse(msg.d);

This is the first time i am playing with Ajax. I am trying to just create a basic login at the moment. Anyways i have the following script..

     <script language = "javascript">
            function Login() {  

                       $.ajax({
                        type: "POST",
                        url: "ajax.aspx/Login",
                        data: '{' +
                                'username:"' + $('#username').val() + '",' +
                                'password:"' + $('#password').val() + '"' +
                               '}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(msg) {
                            alert("alert1");
                            var data = json_parse(msg.d);
                            alert("alert2");
                            if (!data.error) {
                                alert("No Error);
                            }
                           开发者_如何学JAVA else {
                                alert(data.error);
                            }
                        },
                        error: function(msg) {
                            alert('Failure: ' + msg);
                        }
                    });         

            }
    </script>

For some reason it does not run anything after var data = json_parse(msg.d);

It shows the first two alerts but noting after.

the ajax page has the following `

[WebMethod]
public static string Login(string username, string password)
{
    return "{\"error\": \"No IDs\"}";
}


First, JavaScript doesn't have a built-in json_parse() function. Unless you've defined that yourself, it's probably throwing a JavaScript error. The standard client-side utility available in newer browsers is JSON.parse()

More importantly, you've got some redundant serialization going on there. When you're working with ASP.NET ScriptServices and PageMethods, it's important to let ASP.NET's built-in serializer do the work of converting your response to JSON.

Right now, your WebMethod is returning a mess of doubly serialized JSON that looks something like this:

{d:{\"{\"error\": \"No IDs\"}\"}

Since you've set your dataType to json, jQuery is already running a JSON parse operation before your success or error handlers run, but it's only converting the first level of JSON to a JavaScript object. Unfortunately, that only gets it to the point that .d contains yet another JSON string.

If you let ASP.NET do the work for you, you could use something like this in the WebMethod instead:

[WebMethod]
public static string Login(string username, string password)
{ 
  return "No IDs";
}

And then, things will go more smoothly on the client-side:

success: function(msg) {
  if (!msg.d) {
    alert("No Error);
  } else {
    alert(msg.d);
  }
},

If you really want to retain error as the key for the error message, you can do something like this:

[WebMethod]
public static object Login(string username, string password)
{ 
  return new { error = "No IDs" };
}

Or, even use a defined class:

public class ErrorResponse
{
  public string error { get; set; }
}

[WebMethod]
public static ErrorResposne Login(string username, string password)
{ 
  var response = new ErrorResponse();

  response.error = "No IDs";

  return response;
}

In either of those latter cases, you can access the error text through msg.d.error once it hits the client-side.


Whats inside the function json_parse? That function could be the source of your error. A better method to parse JSON is like this.

  1. Go to Douglas Crockford's Github JSON-js/json2.js and copy it
  2. Minify it at jscompress.com and copy the compressed code ( can skip this step )
  3. Paste it somewhere in your Application folder as json2.js
  4. Now reference the script at the page you are pulling data from
    <script src="path/to/script/json2.js" type="text/javascript"></script>

  5. Now inside the function, parse your JSON like this.
    var data = JSON.parse(msg.d);

On an un-related side note, its better if you change your error like this to catch errors effectively.

error: function (xhr, status, error) {
    alert(xhr.statusText);
}

Also, call WebMethod like this.

[WebMethod]
public static string Login(string username, string password)
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    dynamic obj = new ExpandoObject();
    obj.error = "No IDs";
    string str = js.Serialize(obj);
    return str;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜