douzhi2988 2015-01-27 04:35
浏览 82
已采纳

通过$ .ajax()使用GET将数据存储到数据库

I want to save some GET to my database using $.ajax() but the data only returns empty. Here's my code:

$.ajax({
    url: 'file.php?data=',
    type: 'GET',

    data: {
        f: $('input[name="textfield"]').val(),
        c: $('#coordinates').html(),
        a: $('#address').html()
    },

    success: function(s) {
        console.log(s);
    }
});

The PHP part look like this:

if(isset($_GET['data'])) {
    echo $_GET['f'].' - '.$_GET['c'].' - '.$_GET['a'];
}

This code only returns --. What have I missed?

Update The link from the network tab in developer tools in Chrome, shows as follows: http://.../send/data?f=hello&c=62.3875%2C+16.325556&a=KLOCKEN+520%2C+840+13+Tor‌​pshammar%2C+Sverige (send/data is file.php?data=). But when I replace echo $_GET['f']... with var_dump($_GET) it prints the following:

array(1) {
  ["data"]=>
  string(0) ""
}

Why can't I get the data from $_GET['f'], $_GET['c'], and $_GET['a'] with the code above?

  • 写回答

1条回答 默认 最新

  • dsv73806 2015-01-27 06:12
    关注

    Your JS should be:

    $.ajax({
        url: "file.php",
        type: "GET",
        data: ...
    });
    

    You don't need the extra ?data= as part of the URL. That will be generated for you by jQuery. With it, you are overriding your GET request. So, you can see from the URL you posted, you posted a key "data" with no value, so your vardump is indeed showing you a key "data" with no value.

    Your PHP should be:

    if(isset($_GET['f']) && isset($_GET['c']) && isset($_GET['a'])) {
        echo $_GET['f'].' - '.$_GET['c'].' - '.$_GET['a'];
    }
    

    "data" is just the parameter of the jQuery AJAX call - it isn't actually the name of your object.

    You asked about JSON in a comment. Right now, all your data is being sent URL-encoded. To send JSON, a way to do it is:

    var submitPackage = {
        f: JSON.stringify($('input[name="textfield"]').val()),
        c: JSON.stringify($('#coordinates').html()),
        a: JSON.stringify($('#address').html())
    };
    
    $.ajax({
        url: "file.php",
        type: "GET", //Is there a reason you care about doing GET versus POST (the default)?
        data: submitPackage
    });
    

    Then your PHP would be:

    if(isset($_GET['f']) && isset($_GET['c']) && isset($_GET['a'])) {
        echo json_decode($_GET['f']) . ' - ' . json_decode($_GET['c']) . ' - ' . json_decode($_GET['a']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类