【问题标题】:Processing json serialized form data in php在php中处理json序列化的表单数据
【发布时间】:2013-06-12 12:54:07
【问题描述】:

我需要将名为“msg”的 json 字符串中的变量存储在我的数据库中,但我无法使用 $msg = $_POST['msg'];如何正确捕捉?

此外,我想直接在网页上回显 $msg 的内容。

HTML

<div id="addCommentContainer">
    <form id="addCommentForm" action="">
        <textarea name="msg" id="msg" cols="82" title="Your comment" rows="2">Your comment...</textarea>
        <br />
        <input type="text" name="author" title="name" value="<?php echo $_SESSION['username']; ?>" id="author" />
        <br />
        <div id="personal">
            <input type="text" name="city" id="city" title="city (optional)" value="" />
            <br />
            <input type="text" name="email" id="email" title="e-mail (optional)" value="" />
            <br />
            <input type="text" name="url" id="url" title="website (optional)" value="" />
            <input type="hidden" id="cam_id" class="hd" name="cam_id" value="<?php echo $cam_id ?>" />
        </div>
        <input type="submit" id="submit" value="Comment" />
    </form>
</div>

JavaScript

//if submit button is clicked
$('#submit').click(function () {
    //start the ajax
    $.ajax({
        //this is the php file that processes the data 
        url: "/comment/insert.php",
        type: "POST",
        data: $("#addCommentForm").serialize(),
        contentType: "json",
        //success
        success: function (html) {
            //if returned 1/true (process success)
            if (html == 1) {
                //show the success message
                $('.done').fadeIn('slow');
                //if process.php returned 0/false (send mail failed)
            } else alert('Sorry, unexpected error. Please try again later.');
        }
    });
    //cancel the submit button default behaviours
    return false;
});

PHP

 $msg = $_POST['msg'];
//  echo $msg;
 $author = $_POST['author'];
 $email = $_POST['email'];
 $url = $_POST['url'];
 $city = $_POST['city'];




    // include ("/home/sionvalais/domains/skiweather.eu/public_html/v3/functions/strip.php");

    if ($cam_id>1) {

    if ($author=='NAME') {
    $author='Anonymous';
    }

    $host = gethostbyaddr($ip);
    // mysql_query ("set character_set_results='utf8'");
    mysql_query("INSERT INTO sv_review (author,email,msg,cam_id,url,lud)
                    VALUES (
                        N'".$author."',
                        '".$email."',
                        N'".$msg."',
                        '".$cam_id."',
                        '".$url."',
                        NOW()
                    )");
     }

【问题讨论】:

  • 嗯,这很可爱。你的问题是什么?
  • insert.php 上写了什么?/
  • 应该是 $msg = $_POST['msg'];
  • 更多权限显示您的 html 和 php 代码
  • Please, don't use mysql_* functions 在新代码中。它们不再被维护并且是officially deprecated。看到红框了吗?改为了解准备好的语句,并使用pdomysqli

标签: php jquery ajax json


【解决方案1】:

据我所知,contentType 属性的默认值为"application/x-www-form-urlencoded; charset=UTF-8",这在大多数情况下都可以。

但是您发送到服务器的data 似乎不是JSON 对象,设置contentType 不会将数据转换为JSON 对象,它只是声明数据的类型。

所以,如果 data 只是名称/值对的序列化,请删除 contentType: "application/json", 并重试。

如果它是有效的 JSON 类型,则在服务器上解码发布的 JSON 对象,使用:$array = json_decode($json, true);


获取对 JSON 对象的访问权限

您可以按照以下方法在服务器上获取 JSON 对象:

$json = @file_get_contents('php://input');
$array = json_decode($json, true);

// See what happens
print_r($array);

【讨论】:

  • 这是不正确的,dataType: 'json' 指的是响应数据,而不是您发送的数据。它告诉 jQuery 自动解码接收到的 JSON,与您从客户端->服务器发送的内容无关。与$.getJSON() 相同。内容类型是指正在发送的数据。
  • @sharif 如果你能解释你的原因,我将不胜感激
  • 因为这不是问题所说的。问题是将发布数据发送到服务器。我知道如果方法是这样的“PUT”,你可以在服务器中获取表单变量。他使用了 post 方法。所以他仍然可以像你的那样做。我不知道。
  • @sharif,我一开始说的是我不认为data: $("#addCommentForm").serialize() 可能是一个有效的 JSON 对象,它似乎是一对序列化的名称/值。
  • 也不必是因为 datatype:json 表示响应数据类型而不是他发送的序列化数据。thanx @HashemQolami
【解决方案2】:

$POST['msg'] 应该是 $_POST['msg']

还可以输出您的 POST 变量,以便您可以使用以下方法检查它们:

echo print_r($_POST);

【讨论】:

  • echo print_r($var) print_r 默认打印有什么意义,除非你设置 print_r($var, true);
【解决方案3】:

使用必须将数据字符串化为 JSON:JSON.stringify($("#addCommentForm").serializeArray())$("#addCommentForm").serialize() 不生成 JSON。

【讨论】:

  • 好的。完毕。但我没有进入服务器端。
【解决方案4】:

试试这个改变 -

//if submit button is clicked
$('input#submit').click(function () {
//start the ajax
$.ajax({
    //this is the php file that processes the data 
    url: "/comment/insert.php",
    //GET method is used
    type: "POST",
    data: $("form#addCommentForm").serialize(),
    dataType: "application/json",
    //Do not cache the page
    cache: false,
    //success
    success: function (html) {
        //if returned 1/true (process success)
        if (html == 1) {
            //hide the form
            $('.form').fadeOut('slow');
            //show the success message
            $('.done').fadeIn('slow');
            //if process.php returned 0/false (send mail failed)
        } else alert('Sorry, unexpected error. Please try again later.');
    }
});
//cancel the submit button default behaviours
return false;

});

【讨论】:

  • 这个函数 $("#addCommentForm").submit(function(){...}) 而不是 .click 函数呢?
【解决方案5】:

.serialize 形成一个可以发送到服务器的查询字符串。它不会创建 json,但会发出警报 $("#addCommentForm").serialize() 你应该看到一个查询字符串而不是一个 json 所以删除设置 contentType: "application/json", 从 $.ajax 并且您应该能够在 php 中获取$_POST['msg'] 中的味精

【讨论】:

  • 是不是您无法获得 $_POST['msg'] 和所有其他字段(如作者、电子邮件、url ..您可以从 $_POST 获得)?
【解决方案6】:

请勿使用:contentType: "json"

这是一个 POST,对吗?所以,它将使用:

contentType: "multipart/form-data" 

contentType: "application/x-www-form-urlencoded"

或者只是为了简化不要使用某人。 去掉任何contentTypedataType,jQuery默认选择一个,因为类型是POST。

【讨论】:

    猜你喜欢
    • 2016-02-13
    • 2012-03-10
    • 2014-04-14
    • 2015-09-15
    • 2021-08-29
    • 1970-01-01
    • 2016-06-23
    • 2021-09-25
    • 2020-01-05
    相关资源
    最近更新 更多