首页 > 解决方案 > 提交时无法从 HTML 表单获取 jQuery 中的值

问题描述

我还在做一些事情,我几乎已经完成了。我遇到的唯一问题是在我的 jQuery 代码中它不会将值发送到 php 页面。例如:它应该放“?whatever=whatever&soon=soon”,但它没有。它留空。

我尝试过更改代码,例如更改 JS id,并完全更改代码。

$(document).ready(function() {
var $userName = $("username");
var $text = $("text");
var $title = $("title");
var $chatSend = $("#chatSend");

function secret() {
    var userNameString = $userName.val();
    var textString = $text.val();
    var titleString = $title.val();

    $.get("./upload.php", {
        username: userNameString,
        text: textString,
        title: titleString
    });

    window.location.replace("success.php");

    }
}  

我希望它能够输入我的值(到我的 MySQL 表中),但它们都是空白的。

这是我的表格。(当点击 chatSend 时,它会执行 jQuery 函数。)

<div>
<input type="text" id="text" name="text">
                <input type="text" id="title" name="title">
                <input type="text" id="username" name="username" hidden value="<?php echo htmlspecialchars($_SESSION['username']); ?>">
                <button id="chatSend">Send</button>
</div>

另外,这是我现在考虑的上传表单(upload.php):

$user = $_GET['username'];

$title = $_GET['title'];

$text = $_GET['text'];

$query = mysqli_query($con, "INSERT INTO `blog` (username, title, text, view) VALUES ('$user', '$title', '$text', UUID())");

标签: javascriptphpjquerymysql

解决方案


您需要像使用 chatsend 一样使用正确的标识符:

//# = ID
var $userName = $("#username");
var $text = $("#text");
var $title = $("#title");

推荐阅读