简体   繁体   English

有没有比这更好的使用ajax,php和mysql的方法了?

[英]Is there any better way to work with ajax,php and mysql than this?

Let's suppose that I want to have the following small code 让我们假设我想要下面的小代码

<div id="field"> Some links here with a database call. </div>

The problem is that I want to be able to work with ajax on them and call them when the user adds a new link through the appropriate form. 问题是我希望能够在它们上使用ajax并在用户通过适当的表单添加新链接时调用它们。

So instead of having this div, I use a function and call it whenever needed using ajax. 因此,我没有使用这个div,而是使用了一个函数,并在需要时使用ajax对其进行调用。

     <?php  
  function testfield ($id) {  Database call
     ?>
      <div id="field"> <?php The links in here  ?> </div>
      }
   <html>
      <body>
        <?php testfield($_GET['id']); ?> 
     </body>
   </html>

So when a user adds a new link, I just call with ajax the function and I'm set. 因此,当用户添加新链接时,我只需要用ajax调用该函数即可。

Is there any other better way to do this? 还有其他更好的方法吗? Thank you in advance 先感谢您

For example you should use JSON and return data into your div. 例如,您应该使用JSON并将数据返回到div中。 For AJAX try use jQuery. 对于AJAX,请尝试使用jQuery。

PHP code: PHP代码:

$linkarray = array();
$linkarray[] = 'link1';
$linkarray[] = 'link2';
$linkarray[] = 'link3';
echo json_encode($linkarray);

HTML: HTML:

<html>
<body><div id="linklist"></div></body>
</html>

JS: JS:

$.ajax({
 url:'getlinklist.php',
        dataType:'json',
        type:'POST',
        success: function(data){
            $('#linklist').html('');
            $.each(datamfunction(key,value){
                $('#linklist').append(value+'<br/>');                 
            });
        }
    });

当用户添加新链接时,您将使用AJAX将数据发送到与数据库一起使用的PHP脚本,如果成功,则应使用javascript刷新DIV-在DIV末尾写入新信息(您已经拥有此信息),或使用信息,您从JSON大量获取,从PHP脚本成功返回

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM