开发者

AJAX (jQuery) Response

Suppose all forms in your application has this structure:

<div id="result_messages"></div>
<form action="/action">
<!-- all the form -->
</form>

A submit button for this form looks like this:

<input type="button" onclick="$.post( '/action', $(form).serialize(), function (data) {
   $('#result_messages').html( data );      // At this point the 'data' is an standard HTML with a message
});" />

BUT, But not always the response is a message... how to detect when data is a message or not??????:

<input type="button" onclick="$.post( '/action', $(form).serialize(), function (data) {
   if (isMessage( data ))
       $('#result_message开发者_JAVA技巧s').html( data );      
   else
        doActionWith( data );
});" />

Using JSON maybe a solution:

{ response_type : 'message', data: 'all_data_here' }

{ response_type : 'nomessage', data: 'all_data_here' }

Other solution is to put a special STRING at the begin of data:

<!--message--><ul><li>form was processed</li></ul>

Have you other ideas? what do you think about this solutions?


what do you think about this solutions?

<input type="button" onclick="$.post( "/action", $(form).serialize(), function (data) {

  1. That will fall over. The quote before /action will terminate the onclick attribute value
  2. Inline JS is nasty. Bind your event handlers from external scripts.
  3. If JS is not available, this won't work. Write a form that works (with a regular submit button) and then progressively enhance with JS.
  4. form is undefined, that should be this.form
  5. /action is repeating yourself. Write more reusable code: this.form.action

Using JSON maybe a solution

Yes. Use a structured data format instead of a blob of code to shove into the page.


What are the options, other than simple html output? json?

If so, you can send an object back and check it in the callback.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜