无法使用ajax传递值到php

时间:2015-09-19 19:26:08

标签: javascript php ajax

我对ajax完全不熟悉。我想将我的html表单值传递给php,然后从html页面中获取该php页面的输出

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));

2 个答案:

答案 0 :(得分:0)

此时未定义output变量。尝试在回调成功函数中解析响应:

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

答案 1 :(得分:0)

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

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

...但您没有通过$ .ajax发送formData。相反,您要发送其他帖子数据,特别是

{ '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。 - &GT; http://api.jquery.com/jquery.ajax/

更新:逐步示例:

我会尽量让它更容易理解。 初步步骤:

  • 创建一个名为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;

});