简体   繁体   English

在向Ajax提交表单中没有属性

[英]No properties in Submiting a Form to Ajax

So I'm trying to submit a form to an Ajax, but looks like this Ajax does't send nothing to my Json, I tested the result of this Ajax and this is the message I've found in the console "No properties". 因此,我正在尝试向Ajax提交表单,但看起来此Ajax不会向我的Json发送任何内容,我测试了此Ajax的结果,这是我在控制台中找到的消息“无属性” 。

This is the form: 形式如下:

<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: 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 (test): 杰森(测试):

<?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;
}

This Ajax belongs to Update part, there I have a function to update the object from a database. 这个Ajax属于Update部分,我有一个从数据库更新对象的功能。

In your update case's try block, you are spoiling the echo'ed json format because you are echoing ($film_id.$title) . update案例的try块中,您正在破坏echo'ed json格式,因为您正在回显($film_id.$title)

Whenever you want to deliver valid json to your ajax technique, there must be no other text to interfere. 每当您想要将有效的json传递给您的Ajax技术时,都必须没有其他文本来干扰。

If you want to pass additional data, it needs to be built into your json string (not simply appended before it). 如果要传递其他数据,则需要将其内置到您的json字符串中(而不是简单地附加在它之前)。

If you open your browser's dev tools and inspect the XHR tab's details, you should see how the json string is corrupted which causes your process to fail. 如果打开浏览器的开发工具并检查XHR选项卡的详细信息,则应查看json字符串如何损坏,这会导致进程失败。

From https://api.jquery.com/serialize/ : https://api.jquery.com/serialize/

Note: Only "successful controls" are serialized to the string. 注意:只有“成功控件”才被序列化到字符串。 No submit button value is serialized since the form was not submitted using a button. 由于没有使用按钮提交表单,因此没有序列化提交按钮的值。 For a form element's value to be included in the serialized string, the element must have a name attribute. 为了使表单元素的值包含在序列化的字符串中,该元素必须具有name属性。 Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. 仅当选中复选框和单选按钮(“ radio”或“ checkbox”类型的输入)中的值时,才包括这些值。 Data from file select elements is not serialized. 来自文件选择元素的数据未序列化。

So you need to add a couple of name attributes to your form fields. 因此,您需要在表单字段中添加几个name属性。

You've already got a correct answer here, but I wanted to make some comment on your code. 您在这里已经有了正确的答案,但是我想对您的代码发表评论。

First point, since PHP 7.0 (released 4 years ago) we have had the null coalesce operator , to make your variable assignments from POST much shorter. 首先,自PHP 7.0(4年前发布)以来,我们有了null合并运算符 ,以使POST中的变量分配更短。 Second, the idea of DRY means not repeating code over and over again, like you are doing with your calls to json_encode() . 其次, DRY的想法意味着不要一遍又一遍地重复代码,就像对json_encode()调用一样。 Third, whitespace and formatting make a huge difference to how easy your code is to read, and work with. 第三,空格和格式对代码易于阅读和使用产生了巨大的影响。 Here's how I would improve your code: 这是我将改善您的代码的方法:

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

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

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