开发者

javascript callbacks based on html/php output, retrieving variable

I am using jquery to post data from forms (through the jquery form plugin - http://jquery.malsup.com/form/)

The only callbac开发者_运维知识库k that I am able to receive (in the "success:" portion) is the "html" using success: function(html) { ... }.

Can you only differentiate the success response based on the html output?

Basically I want something that can do this..

success: function(html, some_other_variable) {

if (some_other_variable == 1) {

//do something

} else {

//do something else

}

}

I have been reading here: http://api.jquery.com/jQuery.post/ .. but no luck

Thanks in advance, Phil


If I got it right, you could actually send json back, with any param you want. Don't know how the syntax is in PHP is, but in .NET MVC you could do like this.

Ajax call

$.ajax({ dataType: 'json' ... });

Returning result

return Json(new {status = "your status", html = "your html"}, JsonRequestBehavior.AllowGet);

And in your success callback function

  success: function (response) {
    if (response.status == 'success') {
      var html = response.html;
      // do something with html
    } else {
      // do something else
    }
  }

Hope this helps!


The data you return from the server is the data you get in the success method. You can return a different structure which contains your desired status var and the markup you want:

{
  "status": 1,
  "html": "<p>Test</p>"
}

And set your dataType option to 'json'.

Or you could add an output header and ask for that header form the XHR object.


The success function actually responds with 4 parameters, responseText, statusText, xhr object, and a jQuery wrapped form element. (documentation)

If you set the dataType to 'json' then the response coming back will be parsed JSON.

Let's say the page you're doing the POST to responds with

{
   success: true,
   name: 'hello',
   someothervalue: 'world'
}

And your code is...

$('form').ajaxForm({
    dataType: 'json',
    success(response, status, xhr, form) {
        alert(response.name);
    }
});

In that case response would be populated with the json and you could access as shown.

The trick here is that you need whatever the page the form is POST'ing to, to actually return a JSON response.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜