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);
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器