dongyue9860 2011-10-13 18:59 采纳率: 100%
浏览 24
已采纳

如何获取我的jQuery AJAX php代码来更新div?

I have a jQuery call to some PHP which works fine. What I would like to do is to output 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!

  • 写回答

3条回答 默认 最新

  • dongsou8980 2011-10-13 19:02
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录