douzhi2988 2015-01-26 20: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-26 22: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']);
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部