【发布时间】:2021-03-07 18:11:48
【问题描述】:
我正在尝试使用 Javascript 从 HTML 表单中获取信息,将其转换为 JSON 字符串,然后将其发送到 PHP 服务器进行发布,但是,我遇到了接收数据的问题。
当函数 addEmployee() 中的返回值为 false 时,PHP 可以抓取信息但不更新页面。而如果返回值设置为 true,它会更新页面,但无法从客户端获取数据,我需要它来处理两者,所以我很困惑。我也尝试过实现 AJAX 代码,但它似乎不起作用。
HTML 代码:
<!DOCTYPE html>
<html>
<head>
<title>Assignment 7</title>
<link rel="stylesheet" href="style.css" type=text/css>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form id="theForm" action="process.php" method="post">
<fieldset>
<legend>Add an Employee</legend>
<label for="firstName">First Name</label>
<br>
<input id="firstName" name="firstname" type="text">
<br>
<label for="lastName">Last Name</label>
<br>
<input id="lastName" name="lastname" type="text">
<br>
<label for="department">Department</label>
<br>
<select id="department" name="department" id="department">
<option value="Engineering">Engineering</option>
</select>
<br><br>
<input id="submit" type="submit">
</fieldset>
</form>
</body>
</html>
JavaScript 代码:
var employees = [];
function generateID() {
return Math.random().toString().slice(2, 10);
}
function addEmployee() {
'use strict';
var fname = document.getElementById("firstName").value;
var lname = document.getElementById("lastName").value;
var dep = document.getElementById("department").value;
var id = generateID();
for(var i=0; i<employees.length-1; i++){
if(employees[i].id === id) {
id = generateID();
i = 0;
}
}
var employee = {
id:id,
fname:fname,
lname:lname,
dep:dep,
count:employees.length+1
};
employees.push(employee);
var JSONstring = JSON.stringify(employee);
const xhr = new XMLHttpRequest();
xhr.open("POST", "process.php");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSONstring);
return true;
}
function init() {
'use strict';
document.getElementById("theForm").onsubmit = addEmployee;
}
window.addEventListener("load", init);
PHP 代码:
<!DOCTYPE html>
<html>
<head>
<title>PHP</title>
</head>
<body>
<?php
$request = file_get_contents("php://input");
$arr = json_decode($request, true);
$browser = get_browser(null, true);
echo nl2br("Employee Added \r\n");
echo nl2br("Name: " . $arr["lname"] . ", " . $arr["fname"] ."\r\n");
echo nl2br("Department: " . $arr["dep"] ."\r\n");
echo nl2br("Employee ID: " . $arr["id"] ."\r\n");
echo nl2br("Hire Date: " . date("D M j Y") ."\r\n");
echo nl2br("Total Employees: " . $arr["count"] ."\r\n");
echo nl2br($browser["browser"] ."\r\n");
?>
</body>
</html>
我知道我可以直接从 PHP 获取信息,但是向服务器发送 JSON 是我的任务要求之一,所以我别无选择。请帮帮我。
【问题讨论】:
-
java 脚本没有被调用。该表单正在作为表单提交。不确定您要做什么。
-
@JasonK 你确定吗?在 JS 代码中有一个
init方法,它定义了一个onsubmit事件。init在窗口加载时触发。 -
@El_Vanja 没有什么可以阻止默认提交操作继续进行。
-
@JasonK 你好,我相信 javascript 已被执行,因为我能够从文档元素中打印结果。
标签: javascript php html json