简体   繁体   English

jQuery AJAX PHP发布方法问题

[英]JQuery AJAX PHP post method issue

I am trying to post values form HTML file through AJAX as a request and get a JSON formatted string as a response from PHP. 我正在尝试通过AJAX将HTML文件中的值发布为请求,并以JSON格式的字符串作为PHP的响应。

I have done the following 我做了以下

The Javascript file: Javascript文件:

$(document).ready(pageLoad);

function pageLoad()
{
     $("#submit").click(submitClick)
}

function submitClick()
{
    var data = {Year:"2005"};
    $.getJSON("db/connect.php", data, fetchData);
}

function fetchData(data)
{
    $.each(data, function(index, element) { 
        $("#content").append(data[index].Name + "<br />");                                                      
            })
}

The PHP file PHP文件

<?php
$server = "localhost";
$user = "amey";
$pass = "";
$database = "education";

echo $_POST["Year"];

    $conn = mysql_connect($server, $user, $pass) or die("Unable to connect to MySQL");
    mysql_select_db($database, $conn);
    $query = "select * from BabyNames";
    $result = mysql_query($query) or die(error_get_last());

    $json = array();

    while($row = mysql_fetch_array($result))
    {
        $json[] = $row; 
    }

    echo json_encode($json);
    mysql_close($conn);
?>

I can not retrieve the Year value in the PHP file. 我无法在PHP文件中检索Year值。 I've also tried using $.post and $.ajax function. 我也尝试过使用$ .post和$ .ajax函数。 In $.ajax function, when I remove the dataType: "json", the post method works. 在$ .ajax函数中,当我删除dataType:“ json”时,post方法有效。

Please make changes in your code, if your php code working fine. 如果您的php代码工作正常,请更改您的代码。

 $(document).ready(function() {
    var pageLoad = function() {
        $("#submit").click(function(){
          submitClick();
        })
    });
    pageLoad();
 });

if you want submit form/data on click "#submit" then no need to pageLoad function 如果要单击“ #submit”提交表单/数据,则无需pageLoad函数

 $(document).ready(function() {
        $("#submit").click(function(){
          submitClick();
        });
    });
 });

$.getJSON() method does an HTTP GET and not POST. $ .getJSON()方法执行HTTP GET,而不执行POST。 You need to use $.post(). 您需要使用$ .post()。

$.post(url, dataToBeSent, function(data, textStatus) {
  //data contains the JSON object
  //textStatus contains the status: success, error, etc
}, "json");

click here for solution more solution 单击此处获取解决方案更多解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM