dongyongkui6329 2016-10-24 05:56
浏览 54
已采纳

使用ajax将数据从javascript发布到php文件不起作用

When I tried to used ajax to post data from javascript file to php file, there was nothing displayed on php file after using

$_POST['userinput']

Here is the javascript file:

 searchBox.addListener('places_changed', function() {
        var places = searchBox.getPlaces();
        userinput = places[0].name.toString();  // Get user input from search box

        // Pass data to userinput.php via ajax
        $.ajax({
            url: 'userinput.php',
            data: {userinput : userinput},
            type: "POST",
            success: function (result) {
                alert(JSON.stringify(result));
            }
        });

    });

php file:

    if (isset($_POST)) {
        $servername = "localhost";
        $username = "XXXXXXX";
        $password = "XXXXXXXXX";
        $dbname = "CALIFORNIA";

        $city = $_POST['userinput']; // Nothing is posted here

        // Create connection
        $conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);


        $sql = $conn->prepare("SELECT State FROM  CITY as C WHERE   C.City_name=$city");
        $sql->execute();

        $result = $sql->fetchAll();
        $json = json_encode($result);
        echo $json;
    }

I was able to connect to the mysql database. However, there was no data posted from javascript file to php. I'm not sure what to do from this point. the value $city print out nothing. On the client side it printed out an empty object.

  • 写回答

1条回答 默认 最新

  • dsfdsfdsfdsf1223 2016-10-24 06:37
    关注

    in your ajax function try setting dataType property

    $.ajax({
                url: 'userinput.php',
                data: {'userinput' : 'userinput'},
                type: "POST",
                dataType: "text", // add this property
                success: function (result) {
                    alert(JSON.stringify(result));
                }
            });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧