2015-01-27 04:35
浏览 72

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

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

    url: 'file.php?data=',
    type: 'GET',

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

    success: function(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) {
  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:

        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())
        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']);
    点赞 打赏 评论

相关推荐 更多相似问题