【问题标题】:No properties in Submiting a Form to Ajax提交表单到 Ajax 中没有属性
【发布时间】:2020-03-19 14:29:59
【问题描述】:

所以我正在尝试向 Ajax 提交表单,但看起来这个 Ajax 没有向我的 Json 发送任何内容,我测试了这个 Ajax 的结果,这是我在控制台中找到的消息“没有属性”。

这是表格:

<form id="formPrueba" method="POST">
        <input type="text" id="film_id">
        <input type="text" id="title">
        <input type="submit" name="sub">
        <button form="formPrueba" onclick="editar()"></button>
</form>

Ajax 函数:

function editar(){
    event.preventDefault();
    $.ajax({
        method: "POST",
        url: "prueba.php",
        data: $("#formPrueba").serialize(),
        dataType: "json"
    })
        // en caso de éxito
        .done(function (response) {
            // Escribe el mensaje recibido en el JSON descartando el contenido anterior
            console.log("Response de Edit".response);

        })
        // En caso de fallo
        .fail(function (jqXHR, textStatus, errorThrown) {
            alert("Error: " + textStatus);
        });
}

Json(测试):

<?php
echo ("Esto es prueba");
echo json_encode($_POST);

json:

<?php
include "class/Film.php";
require_once "class/DBSingleton.php";
//Json
$film_id = (isset($_POST['film_id'])? $_POST['film_id'] : null);
$title = (isset($_POST['title'])? $_POST['title'] : null);
$description = (isset($_POST['description'])? $_POST['description'] : null);
$release_year = (isset($_POST['release_year'])? $_POST['release_year'] : null);
$language_id = (isset($_POST['language_id'])? $_POST['language_id'] : null);
$original_language_id = (isset($_POST['original_language_id'])? $_POST['original_language_id'] : null);
$rental_duration = (isset($_POST['rental_duration'])? $_POST['rental_duration'] : null);
$rental_rate = (isset($_POST['rental_rate'])? $_POST['rental_rate'] : null);
$length = (isset($_POST['length'])? $_POST['length'] : null);
$replacement_cost = (isset($_POST['replacement_cost'])? $_POST['replacement_cost'] : null);
$rating = (isset($_POST['rating'])? $_POST['rating'] : null);
$special_features = (isset($_POST['special_features'])? $_POST['special_features'] : null);
$image = (isset($_POST['image'])? $_POST['image'] : null);
$last_update = (isset($_POST['last_update'])? $_POST['last_update'] : null);

switch ($_POST["action"]) {
    case 'listado':
        try {
            $response["msg"]="Listado de las Peliculas.";
            $response["success"]=true;
            $response["data"]=Film::list();
        } catch (Exception $e) {
            $response["success"]=false;
        }
        echo json_encode($response); 
    break;
    case 'insert':
        try {
            $response["msg"]="Insertar.";
            $response["success"]=true;
            $instanciaPelicula=new Film($film_id,$title,$description,$release_year,$language_id,$original_language_id,$rental_duration,$rental_rate,$length,$replacement_cost,$rating,$special_features,$image,$last_update);
            $instanciaPelicula->insert();  
        } catch (Exception $e) {
            $response["success"]=false;
        }  
        echo json_encode($response); 
    break;
    case 'delete':
        try {
            $response["msg"]="Eliminar.";
            $response["success"]=true;
            $instanciaPelicula=new Film($film_id);
            $instanciaPelicula->delete();
        } catch (Exception $e) {
            $response["success"]=false;
        }  
        echo json_encode($response); 
    break;
    case 'update':
        try {
            $response["msg"]="Actualizar.";
            $response["success"]=true;
            $instanciaPelicula=new Film($film_id,$title,$description,$release_year,$language_id,$original_language_id,$rental_duration,$rental_rate,$length,$replacement_cost,$rating,$special_features,$image,$last_update);
            $instanciaPelicula->update();
            echo ($film_id.$title);
        } catch (Exception $e) {
            $response["success"]=false;
        }  
        echo json_encode($response); 
    break;
    case 'paginacion':
        try {
            $response["msg"]="Paginar.";
            $response["success"]=true;
            $peliculas=Film::paginacion();
        } catch (Exception $e) {
            $response["success"]=false;
        }  
        echo json_encode($response); 
    break;
    case 'select':
        try {
            $response["msg"]="Seleccionar.";
            $response["success"]=true;
            $response["data"]=Film::select($film_id);
        } catch (Exception $e) {
            $response["success"]=false;
        }  
        echo json_encode($response); 
    break;
    default:
        # code...
    break;
}

这个 Ajax 属于更新部分,我有一个从数据库更新对象的功能。

【问题讨论】:

    标签: javascript php jquery ajax post


    【解决方案1】:

    在您的update 案例的try 块中,您破坏了回显的json 格式,因为您正在回显($film_id.$title)

    只要您想将有效的 json 传递给您的 ajax 技术,就不能有其他文本干扰。

    如果你想传递额外的数据,它需要被构建到你的 json 字符串中(而不是简单地附加在它之前)。

    如果您打开浏览器的开发工具并检查 XHR 选项卡的详细信息,您应该会看到 json 字符串是如何损坏的,从而导致您的进程失败。

    来自https://api.jquery.com/serialize/

    注意:只有“成功的控件”被序列化为字符串。由于未使用按钮提交表单,因此没有序列化提交按钮值。 对于要包含在序列化字符串中的表单元素的值,该元素必须具有名称属性。 来自复选框和单选按钮(“radio”或“checkbox”类型的输入)的值仅在以下情况下包含他们被检查了。来自文件选择元素的数据未序列化。

    因此,您需要在表单字段中添加几个 name 属性。

    【讨论】:

    • 嗨,米克,问题是当我尝试检查 XHR 选项卡的详细信息时,我只看到“prueba.php”(测试)json 中的“无属性”消息...另一件事,当我提交参数时,我得到一个解析错误。
    • 这个测试很糟糕,原因与我在回答中解释的原因相同。 echo ("Esto es prueba"); echo json_encode($_POST); 应该是 echo json_encode(["Esto es prueba", $_POST]); 以便所有数据都在 json 格式的字符串中。
    【解决方案2】:

    您已经在这里得到了正确答案,但我想对您的代码发表一些评论。

    第一点,自 PHP 7.0(4 年前发布)以来,我们已经有了 null coalesce operator,以使您从 POST 中的变量分配更短。其次,DRY 的概念意味着不要一遍又一遍地重复代码,就像你对json_encode() 的调用一样。第三,空格和格式对您的代码阅读和使用的难易程度有很大影响。以下是我将如何改进您的代码:

    <?php
    include "class/Film.php";
    require_once "class/DBSingleton.php";
    //Json
    $film_id              = $_POST['film_id'] ?? null;
    $title                = $_POST['title'] ?? null;
    $description          = $_POST['description'] ?? null;
    $release_year         = $_POST['release_year'] ?? null;
    $language_id          = $_POST['language_id'] ?? null;
    $original_language_id = $_POST['original_language_id'] ?? null;
    $rental_duration      = $_POST['rental_duration'] ?? null;
    $rental_rate          = $_POST['rental_rate'] ?? null;
    $length               = $_POST['length'] ?? null;
    $replacement_cost     = $_POST['replacement_cost'] ?? null;
    $rating               = $_POST['rating'] ?? null;
    $special_features     = $_POST['special_features'] ?? null;
    $image                = $_POST['image'] ?? null;
    $last_update          = $_POST['last_update'] ?? null;
    
    // assume true, so you don't have to type it every time
    $response = ["success" => true];
    
    // since we are checking for exceptions in every block, just wrap it all in one try block
    try {
    
        switch ($_POST["action"]) {
            case 'listado':
                $response["msg"] = "Listado de las Peliculas.";
                $response["data"] = Film::list();
            break;
    
            case 'insert':
                $response["msg"] = "Insertar.";
                // you can't read lines that are 300 characters long
                $instanciaPelicula = new Film(
                    $film_id, $title, $description, $release_year, $language_id,
                    $original_language_id, $rental_duration, $rental_rate, $length,
                    $replacement_cost, $rating, $special_features, $image, $last_update
                );
                $instanciaPelicula->insert();
            break;
    
            case 'delete':
                $response["msg"] = "Eliminar.";
                $instanciaPelicula = new Film($film_id);
                $instanciaPelicula->delete();
            break;
    
            case 'update':
                $response["msg"] = "Actualizar.";
                $instanciaPelicula = new Film(
                    $film_id, $title, $description, $release_year, $language_id,
                    $original_language_id, $rental_duration, $rental_rate, $length,
                    $replacement_cost, $rating, $special_features, $image, $last_update
                );
                $instanciaPelicula->update();
            break;
    
            case 'paginacion':
                $response["msg"] = "Paginar.";
                $peliculas=Film::paginacion();
            break;
    
            case 'select':
                    $response["msg"] = "Seleccionar.";
                    $response["data"] = Film::select($film_id);
            break;
    
            default:
                # code...
            break;
        }
    
    } catch (Exception $e) {
        $response["success"] = false;
        // you may not want to use the message directly, but you should
        // have some indication from the server of what the error was
        $response["error"] = $e->getMessage();
    }
    
    // set the correct header for the data you're sending
    header("Content-Type: application/json");
    echo json_encode($response);
    

    【讨论】:

    • 谢谢你,Miken,我是学生,所以这对我很有用。
    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2020-08-03
    相关资源
    最近更新 更多