开发者

AJAX Post to self in PHP

I fee开发者_如何学Gol like this is something that I should have learned by now, and I'm sure it's something small I'm missing, but I could use clarification to make sure my approach is correct.

I'm using AJAX to post data to self which is a file that contains php and html. I can write the php fine, but after a successful ajax post, how do I only return the data that is processed via php and not the remaining html? Is it better to just post to a separate script?


If you have the PHP handling the POST request in the beginning of the file, you can just do something like this:

<?php
    if (isset($_POST['somevar'])) {
        /* do something */
        exit(0);
    }
?>

exit() will stop the loading of the page at that line.

I, for one, think it's better to be utilizing a separate script to deal with dynamic AJAX requests.


You can scrape changed parts of the resulting document and insert them into the original page. This way you can also make your page work for a user with JavaScript disabled not doing anything specially.

Example:

<html><title>Unobtrusive AJAX Example</title>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script><script type="text/javascript">

$("form.ajax[id]").live('submit', function() {
        $(this).find("input[type='submit']").attr("disabled", true);
        $.ajax({
            type: $(this).attr('method') || 'POST',
            url: $(this).attr('action') || window.location.pathname,
            data: $(this).serialize(),
            context: $(this), 
            success: function(data) {
                $(this).html(
                    $(data).find("#" + $(this).attr("id")).html()
                );
            }
        });
    return false;            
});
</script>
</head><body>
<div><form method="post" class="ajax" id="main">
    <p><?php echo date('H:i:s'); ?></p>
    <p><input type="submit"></p>
</form></div>
<!-- keep the div: you got to have at least one div to make it work -->
</body></html>


It always depends on what are your needs, but if using the same script is enough for you then do it.

If you want the script not to send anything more than your answer to an XML HTTP Request, after sending the data, use an exit(); in PHP, which will make the script finish at that point.


Put to the of the script:

if($_POST['id']) {

$data = array('return'=>'returnValue');
$data = json_encode($data);

exit($data); }

Javascript:

$.ajax({
    url: 'frmSelf.php',
    data: $("#frmSelf").serialize(),
    dataType: 'json',
    type : 'post',
    success : function(returnData) {
        console.log(returnData);
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜