jquery - 将 Json 数据从我的 html 页面发送到 php
问题描述
我从stackoverflow中获取了一个代码并创建了一个“index.htm”页面,它还将一个json数据从html页面发送到php这里它是“test.php”
当我尝试提交数据并在 Web 开发工具中查看时,我总是收到此错误:
jquery.min.js:4 从源“null”访问“file:///C:/Users/1701053/Desktop/ClientServer%20demo/test.php”处的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求是仅支持协议方案:http、data、chrome、chrome-extension、https。
这是我的代码
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
测试.php
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
?>
注意:这不是我自己的工作,我将其用作参考,以了解如何仅使用 javascript 将 Json 对象实际发送到服务器
解决方案
简单地说,XMLHttpRequest()
当 URL 以file:///
. 功能也$.ajax()
没有用。
XMLHttpRequest()
适用于http://
或https://
URL,因此请尝试从任何Web 服务器(如XAMPP )运行此页面
推荐阅读
- python - Sagemaker XGBoost 超参数调整错误
- android - 设置 AppCompat Spinner 背景颜色的样式
- .net-core - 为什么在 Entity Framework Core 中使用 FindAsync 时出现空引用异常?
- javascript - 在 php 表单提交后使用自定义消息重定向到 html
- python - 如何在将aws lambda与django一起使用时从s3访问google电子表格json文件
- java - JDBC MySQL 在代码之外配置用户名/密码凭证
- react-native - RN ScrollView 减少所需的滑动量
- java - 为什么JVM找不到SpringApplication类的定义?
- bootstrap-4 - 在行阈值上方的表格列中隐藏和显示项目
- scala - 如何在 scaladocs 中链接另一个对象内的变量?