gpt4 book ai didi

javascript - 在不离开页面的情况下将数据从html发送到php页面

转载 作者:行者123 更新时间:2023-11-28 15:34:55 25 4
gpt4 key购买 nike

我已经在堆栈溢出和谷歌搜索中花费了大量时间来完成此任务。但它们对我来说都不起作用。

我有一个 html 表单,我需要在不离开页面的情况下将数据发送到 php。我使用了 ajax 和 javascript。我可以通过离开页面来发布数据,但我不想离开页面。

这是我的 html:

<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/topcoat-mobile-light.css" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<script src = "js/jquery.js"></script>
<script type="text/javascript" src = "js/index.js"></script>
<meta name="msapplication-tap-highlight" content="no" />
<title>Title</title>
</head>
<body>
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Header</h1>
</div>
</div>
<div class = "content text-input">
<form id = "form" name = "form" action="http://localhost/index.php" method = "post">
<p>Please fill the details.
<p> Name</p>
<input type="text" class="topcoat-text-input" placeholder="text" value="" id = "name" name = "name">
<input id = "submit" type="submit" class="topcoat-button" value = "Submit">
</form>
<script type="text/javascript">
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});

ev.preventDefault();
});
</script>
</div>
</body>
</html>

我可以通过离开页面后通过post访问php中的“名称”,所以我不会在这里发布php。任何帮助将不胜感激。如果有人需要澄清,我就在这里。

最佳答案

虽然您的输入有 id,但它们没有 name 属性。 Serialize 使用名称来创建数据的键值对。

参见:http://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. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

将您的输入更改为:

<input type="text" class="topcoat-text-input" placeholder="text" value="" id="name" name="name"/>

关于javascript - 在不离开页面的情况下将数据从html发送到php页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25947399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com