weixin_33716557 2014-10-25 05:08 采纳率: 0%
浏览 31

如何使用AJAX获取MySql

I have a MySql table as:

id           Name
1            John
2            Ray
3            Tom

And this is code for front end html file used to called the ajax and display result:

<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.6.2.js"></script>
<script language="javascript" type="text/javascript" src="ajax.js"></script>
</head>
<body>
<input type="button" value="Click Here" id="ajaxButton"/>
<div id="result"></div>
</body>
</html>

I want to create a client sided script to display the table as random order every time the user refreshes:

 2            Ray 
 1            John
 3            Tom

Here is the script which will be retriving the data from MySql:

$(document).ready(function() {
    $("#ajaxButton").click(function() {
        $.ajax({
              type: "Post",
              url: "employee.php",
              success: function(data) {
                    var obj = $.parseJSON(data);      


               --CODE HERE---


              }
        }); 
    });
});

Pleas help as to what should be written in place of ---CODE HERE---- to get the random table as mentioned before.

  • 写回答

1条回答 默认 最新

  • weixin_33725722 2014-10-25 05:42
    关注

    As suggested by @Barmar, to get random results, add ORDER BY RAND() in your mysql query. If you want to use it only using javascript, try this solution: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array

    If your JSON is in format: [{id: 1, name: 'John'},{id: 2, name: 'Ray'}]

    Try this code in JS:

    $(document).ready(function() {
        $("#ajaxButton").click(function() {
            $.ajax({
                  type: "POST",
                  url: "employee.php",
                  success: function(data) {
                        var obj = $.parseJSON(data);      
                        var str = '<table>';
                        for(i in obj)
                        {
                         str+='<tr><td>'+obj[i].id+'</td><td>'+obj[i].name+'</td></tr>';
                        }
                        str+='</table>';
    
                       $('#result').html(str);
                  }
            }); 
        });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 优质github账号直接兑换rmb,感兴趣伙伴可以私信
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)