开发者

How to get my jQuery AJAX php code to update a div?

I have a jQuery call to some PHP which works fine. What I would like to do is to output 开发者_JAVA百科the new contents of a particular div right from the php using the echo statement. Is that possible?

Previously I used to return the new contents of the div using JSON encoding like this:

$rows = array();
while($r = mysql_fetch_assoc($result))
{
        $rows[] = $r;
}

echo json_encode($rows);

But now I want to call a PHP function which is used elsewhere to create div contents, and I want that to be the only place where those div contents are made.

Is it possible to do what I am trying?

Thanks!


Yes, this is possible. Remember that the parameter to your jQuery success function contains all of the output from your back-end script. Simply replace the html of the container you want with the contents of the parameter.

PHP (someUrl.php):

echo('<div>Hello World!</div>');

JavaScript:

var YourDataString = '';
$.ajax({
    type: 'GET',
    url: 'someUrl.php',
    data: YourDataString,
    success: function(html) {
        $('#someContainer').html(html);
    }
});

This will put '<div>Hello World</div>' inside of the element with the id: someContainer

Edit

When I have problems (like stuff not appearing) with AJAX requests, it helps me if I visit the page I am calling directly to see what output is being generated. If I don't turn on error reporting and I see nothing but a white screen, then I know there's an error in my PHP and nothing is being output because of it.

You can try turning on error reporting in your script to see if there is an error. If you cannot find one, comment your entire script out and put a single echo('I am here!'); in there and see if that makes it to your page. If it does, then you know that there's an error in your PHP somewhere.

You can also look at your browser's error console to see if your JavaScript is throwing any errors. Try a more simplistic example first if you can't quite wrap your head around it yet. The code above should work.


You can use jquery.ajax to update content from a php file:

http://api.jquery.com/jQuery.ajax/


$rows = array();
while($r = mysql_fetch_assoc($result))
{
        $rows[] = $r;
}

echo json_encode($rows);
die();enter code here

you need to die() or exit 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜