weixin_33682790 2014-12-15 11:32 采纳率: 0%
浏览 44

通过AJAX将MySQL / PHP转换为jQuery

I'm saving highscores in a mysql database via PHP. I need to send scores back to my app but It's not working.

This is the first time I'm working with PHP and JSON.. so here is my code

PHP:

   <?php 
    $server = "...";
    $user = "...";
    $pass = "...";
    $bd = "...";

    $conexion = mysqli_connect($server, $user, $pass,$bd) 
    or die("Ha sucedido un error inexperado en la conexion de la base de datos");

    $sql = 'SELECT * FROM table_one ORDER BY score DESC LIMIT 10';

    if(!$result = mysqli_query($conexion, $sql)) die();
    $scores = array(); 
    while($row = mysqli_fetch_array($result)) 
    { 
        $name=$row['name'];
        $score=$row['score'];
        $scores[] = array('name'=> $name, 'score'=> $score);
    }
    $close = mysqli_close($conexion) 
    or die("Ha sucedido un error inexperado en la desconexion de la base de datos");

    $json_string = json_encode($scores);
    header('Content-Type: application/json');
    echo $json_string;
 ?>

JQUERY

$.ajax({
                method: 'GET',
                url: 'score2.php',
                dataType: 'json',
                success: function(result) {
                var data = jQuery.parseJSON(result);
                console.log(data);

                }

any help please?

  • 写回答

1条回答 默认 最新

  • weixin_33725807 2014-12-15 11:37
    关注

    First of all you can remove the header('Content-Type: application/json'); line from your PHP, you simply don't need it.

    In your JavaScript you don't need to parse the result using $.parseJSON because by setting the dataType field to JSON you're telling jQuery you expect a JSON string as a result, and so it automatically parses the result for you. Try this:

    $.ajax({
        method: 'GET',
        url: 'score2.php',
        dataType: 'JSON',
        success: function(data) {
            console.log(data);
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!