开发者

Can I get jQuery's load(url) to give me success/error feedback from the response?

I'm basically using a plug-in that makes use of the jQuery load(url) function.

Since .load() allows you to use a callback function with the response as parameter, I was wondering if there is a way to embed, for example, a variable indicating error or success in the file .load() is calling?

In the file that is called you could use something like $.myPlugin.response = "An error occured" and the callback function will be able to read it (At least in firefox). The problem however is that $.myPlugin.response now is global and if we were to make two .load() simultaneously we wouldn't be able to tell which call went bad.

Is there a way to contain this error variable within the callback function or at least in a tighter scope than global?

开发者_Python百科

One way would be to parse the response with regex and look for a specific expression, but that does not feel like the right way to do it.

Could the use of custom headers work out somehow?

I hope the question makes sense

Cheers


Let's start with one of the examples from the documentation for .load():

<!DOCTYPE html>
<html>
<head>
  <style>
  body{ font-size: 12px; font-family: Arial; }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>

<b>Successful Response (should be blank):</b>
<div id="success"></div>
<b>Error Response:</b>
<div id="error"></div>

<script>
$("#success").load("/not-here.php", function(response, status, xhr) {
  if (status == "error") {
    var msg = "Sorry but there was an error: ";
    $("#error").html(msg + xhr.status + " " + xhr.statusText);
  }
});
  </script>

</body>
</html>

Now we'll modify the script deal with a custom error that is returned by the web server or CGI script:

<script>
$("#success").load("/not-here.php", function(response, status, xhr) {
  if (status == "custom_error") {
    // the handler for custom_error goes here
  }
});
  </script>


You can tell jQuery to call a function whenever an Ajax call ends with an error response (see ajaxSetup):

$.ajaxSetup({
    error: function(xhr, textStatus, errorThrown) {
            alert(xhr.responseText)
    }
});

Of course you must return a HttpServerError to achieve this result (how to do this depends on the server-side framework).

E.g. using Django:

from django.http import HttpResponse, HttpResponseServerError

def myAjaxCall(request):
    """ Return the result if present;
        if not present, return an error with the string "No value to return"
        in case of any other error, return the error with its text.
    """
    try:
        value = compute_my_value(request)
        if not value:
            raise Exception, 'No value to return!'
        return HttpResponse(value, mimetype="application/json")

    except Exception, e:
        return HttpResponseServerError(unicode(e))
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜