weixin_33682790 2017-12-26 22:25 采纳率: 0%
浏览 187

AJAX如何使用key:value

My form:

<form action="html_post.php" method="post" id="myform">

    <textarea id="textarea" placeholder="Add your comment" name="posting"> </textarea>

    <input class="button" type="button" name="send" value="Send">
</form>

I have such code

$(".button").click(function () {

    var content = $("#myform").serialize();

    $.ajax({
        url: "add_post.php",
        type: "POST",
        data: {
            text: content,
            action: "add_post"
        },
        success: function () {
            $('#comment_block').load('list_post.php');
            document.getElementById('textarea').value = "";
        }
    })

});

And such php:

echo mysqli_error($connection);
if (strlen($_POST['posting']) >= 5) {
    $text = htmlspecialchars($_POST['posting']);
    $insert = "INSERT INTO post(content) VALUE ('$text')";
    mysqli_query($connection, $insert);
}

But it does not add text to db. I'm just learning ajax and it's my first experience with key:value so can you help me?

And yep, there is no shown errors

  • 写回答

2条回答 默认 最新

  • 笑故挽风 2017-12-26 22:46
    关注

    Based on your posted code, on the server there will be two keys set in the $_POST variable. These are the ones that you define at your ajax request in javascript: text and action.

    So while you check $_POST['posting'] it does not exists, but there are $_POST['text'] and $_POST['action']. $_POST['text'] will contain all the form fields as an URL-encoded string, like "posting=xyz". In order to access these values, you could use the parse_str() php function that parses this string as it were a query string.

    So the condition at the server side could be something like as follows.

    if (isset($_POST['text'])) {
        // $formdata passed in by reference, it will contain all the form fields
        parse_str($_POST['text'], $formdata);
    }
    
    if (isset($formdata['posting']) && strlen($formdata['posting']) >= 5) {
        // Perform db operation
    }
    
    评论

报告相同问题?