无法使用ajax向php传递值

Unable to pass value using ajax to php

本文关键字:php ajax      更新时间:2023-09-26

我对ajax完全陌生。我想将html表单值传递给php然后将php页面的输出返回到html页面

Ajax代码

 $("#submit1").click(function(){
 var formData = $("#add-cart-form").serialize();
 $.ajax({
    type: 'POST',
    url: 'test.php',
    dataType : 'json',
    data: {
        'total_load' : $('#total_load').val(),
        'hours' : $('#hours').val(),
    },
     success: function (data) {
       alert(data)
     },
  });
 var result = $.parseJSON(output);
 alert(result[0]);
});

相关php代码

$connected_load = $_POST['total_load'];  $no_of_hours = $_POST['hours'];

 echo json_encode(array(
     $connected_load, 
     $selected_inverter["model"], 
     $selected_inverter["voltage"], 
     $selected_inverter["type"],
     $no_of_hours,$selected_battery));

恕我直言,代码有一些不准确之处。首先,你在写:

var formData = $("#add-cart-form").serialize();

…但您不是通过$.ajax发送formData。相反,您将发送其他post数据,特别是

{ 'total_load' : $('#total_load').val(), 'hours' : $('#hours').val(),}

…对象内部有一个错误,右花括号前有一个逗号

无论如何,这是正确的做法(js)

$("#submit1").click(function(event){
    // perhaps formData form embrace "total_load" and "hours" ?
    var formData = $("#add-cart-form").serialize();
    $.ajax({
        url: 'test.php',
        cache: false, // optional
        async: true, // optional, defaults to true. False value will make ajax synchronous, hanging the browser.
        data: formData,
        type: 'post',
        dataType : 'json'
    }).done(function(d){ // trying to simplify comprehension of the console.log output, below...
        console.log(d.d_connected_load);
        console.log(d.d_model);
        console.log(d.d_voltage);
        console.log(d.d_type);
        console.log(d.d_no_of_hours);
        console.log(d.d_selected_battery);
    }).fail(function(j,s,e){
        console.warn(j.responseText);
    });
});

和,PHP端:

<?php
    $connected_load = $_POST['total_load'];
    $no_of_hours = $_POST['hours'];
    # stuffs here for sanitizing $_POST and working on $selected_inverter["model"], $selected_inverter["voltage"], $selected_inverter["type"], $selected_battery
 echo json_encode(
    array(
        "d_connected_load" => $connected_load, 
        "d_model" => $selected_inverter["model"], 
        "d_voltage" => $selected_inverter["voltage"], 
        "d_type" => $selected_inverter["type"],
        "d_no_of_hours" => $no_of_hours,
        "d_selected_battery" => $selected_battery
        )
    );

不需要解析JSON。当你在ajaxcall选项中指定dataType:'json'进行ajax调用时,jQuery会为你做这件事(显然,从php返回的json必须是格式良好的)。

另外,请注意ajax调用的编写方式。在最新的jQuery版本中,最好是使用.done().fail()承诺方法来代替successfail。-> http://api.jquery.com/jquery.ajax/

UPDATE: STEP BY STEP示例:

我尽量让它更容易理解。最初的步骤:
  • 创建一个名为form.php的文件;
  • 创建一个ajax_test.php文件;创建test.js文件

====== FILE FORM.PHP ======
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
    <form id="add-cart-form" method="post">
        <p>TOTAL LOAD: <input type="text" value="total load" name="total_load" /></p>
        <p>TOTAL LOAD: <input type="text" value="hours!" name="hours" /></p>
        <hr />
        <button type="submit" id="submit1">SUBMIT</button>
    </form>
</body>
<script type="text/javascript" src="js/test.js"></script>
</html>

====== FILE AJAX_TEST.PHP ======
<?php
    $connected_load = $_POST['total_load'];
    $no_of_hours = $_POST['hours'];
    # stuffs here for sanitizing $_POST and working on $selected_inverter["model"], $selected_inverter["voltage"], $selected_inverter["type"], $selected_battery
 echo json_encode(
    array(
        "d_connected_load" => $connected_load, 
        "d_model" => $selected_inverter["model"], 
        "d_voltage" => $selected_inverter["voltage"], 
        "d_type" => $selected_inverter["type"],
        "d_no_of_hours" => $no_of_hours,
        "d_selected_battery" => $selected_battery
        )
    );

====== FILE TEST.JS ======
$("#submit1").click(function(event){
   // perhaps formData form embrace "total_load" and "hours" ?
    var formData = $("#add-cart-form").serialize();
    $.ajax({
        url: 'ajax_test.php',
        cache: false, // optional
        async: true, // optional, defaults to true. False value will make ajax synchronous, hanging the browser.
        data: formData,
        type: 'post',
        dataType : 'json'
    }).done(function(d){ // trying to simplify comprehension of the console.log output, below...
        console.log(d.d_connected_load);
        console.log(d.d_model);
        console.log(d.d_voltage);
        console.log(d.d_type);
        console.log(d.d_no_of_hours);
        console.log(d.d_selected_battery);
    }).fail(function(j,s,e){
        console.warn(j.responseText);
    });
    event.preventDefault();
    event.stopImmediatePropagation();
    return false;
});

此时还没有定义output变量。尝试解析回调成功函数中的响应:

success: function (data) {
     var result = $.parseJSON(data);
     console.log(result[0]);
}