开发者

Select only part of a HTML page with jQuery's .post() method?

开发者 https://www.devze.com 2023-02-26 15:43 出处:网络
I have a website that has a voting poll module. A poll controller accepts a vote via a POST request containing the poll ID and response ID as parameters to http://example.com/poll.

I have a website that has a voting poll module. A poll controller accepts a vote via a POST request containing the poll ID and response ID as parameters to http://example.com/poll.

The site-wide template of this site features the current poll in the sidebar; its a simple form with the action attribute set to the aforementioned URL. I am, however, highjacking this with jQuery to submit poll votes asynchronously.

This is the function I have thus far:

$('form.poll').submit(function() {
    var form = this;
    var response = $('div.response', form);
    if ($('input:checked', form).length == 0) {
        response.fadeOut('fast', function() {
            $(this).html('<p class="error">Please select an option.</p>').fadeIn('fast');
        })
    }
    else {
        var action = $(form).attr('action');
        $.post(action, $(form).serialize(), function(data) {
            alert('Data loaded: ' + data);
        });
        $('fieldset', form).fadeOut('fast');
        response.fadeOut('fast', function() {
            $(this).html('<p class="success">Vote successfully added.</p>').fadeIn('fast');
        });
    }
    return false;
});

As you can see, it merely intercepts a form being sub开发者_运维技巧mitted and then executes the POST using jQuery rather than a full page request, so the visitor never leaves the page they're on.

My problem is: the whole page's HTML comes back in the $.post response (the line with the alert() call). How can I pick out the content of the #content <div> tag of the HTML that is returned, to be used as a response in my poll form? The mark-up for the poll form is:

<form action="/poll" method="post" id="poll" class="poll"> 
  <h3>Poll</h3> 
  <p class="question">Who do you think will win the Lockdown main event?</p> 
  <div class="response"><!--//--></div> 
  <fieldset> 
    <input type="hidden" name="poll" value="1" /> 
    <ul class="options"> 
      <li><label for="option_1"><input type="radio" name="response" value="1" id="option_1" /> Mr Anderson</label></li> 
      <li><label for="option_2"><input type="radio" name="response" value="2" id="option_2" /> Rob Van Dam</label></li> 
      <li><label for="option_3"><input type="radio" name="response" value="3" id="option_3" /> Sting</label></li> 
    </ul> 
    <input type="submit" name="vote" value="Vote" class="button" /> 
  </fieldset> 
</form>

And I want to insert the response into the aptly-named .response div tag. Any help, pointers, or suggestions would be much appreciated.


// just to be sure that it's of dataType html already
var data = $(data).html(); 

// grab element's content
var content = $(data).find('#content').html();

alert(content);

Find working demo here: http://jsfiddle.net/ezmilhouse/BSrk6/


A better solution would be to detect that it is an AJAX request server-side and only return the content you need, many frameworks have this built in but you could manually implement something similar by checking for the HTTP_X_REQUESTED_WITH header added by most major JS frameworks (including jQuery) when performing AJAX requests.

A rubbish example in PHP would be something along the lines of:

<?php if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest' ) : ?>
  <html>
    <head/>
    <body>
<?php endif ?>

      <p>Martin's form stuff!</p>

<?php if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest' ) : ?>
    </body>
  </html>
<?php endif ?>


If data contains all the HTML, then this:

$(data).find("#content")

should give you access to just the #content div, I think. Not very nice as it needs to parse the entire HTML.


I've had issues with using .find()/.filter() on data return from an AJAX request so I have used the following method.

What you might want to do is apply the data to a new, hidden, temp element and then access it as usual from there.

$.post(action, $(form).serialize(), function(data) {
    // create the new element, might want to generate a unique / random name
    $('body').append('<div id="temp_element' style="display: none;"></div>');        
    // apply the response data to the temp element
    $('#temp_element').html(data);
    // Martin, did you mean #content... or #response as I have it here?
    // alert out only the element you need
    alert( $('#response', '#temp_element').html();
    // remove the temp element
    $('#temp_element').remove();
});
0

精彩评论

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