javascript - 从 JS 到 PHP 的 AJAX POST 是空的
问题描述
索引.html:
<script>
function myFunction() {
var srcd = document.getElementById("two").src;
$.ajax({
type: "POST", //type of method
url: "/file.php", //your page
data: {
src: srcd
}, // passing the values
success: function(res) {
location.reload();
}
});
}
</script>
文件.php:
<?php
header('Access-Control-Allow-Origin: *');
$src = $_POST["src"];
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode( $jsonString, true );
foreach ( $data as $key => $entry )
{
if ( $entry['src'] == $src )
{
$data[$key]['counter']++;
}
}
$newJsonString = json_encode( $data );
file_put_contents( 'jsonFile.json', $newJsonString );
?>
但是我已经意识到$src
在 PHP 中是空的。变量没有赋值。我知道 POST 请求发生的事实,好像访问控制标头不存在于file.php
中,控制台中出现错误。
如果我直接为 PHP 文件分配一个值并运行它,比如$src = 'https://someurl.com/';
,它会按预期工作。
我怎样才能解决这个问题?
谢谢。
解决方案
推荐阅读
- linux - 如何将文件夹从linux机器转移到windows
- android - Android Studio 附加到进程未找到本机符号
- python - python 3.6 和更早版本与 3.7 中不可变对象的“is”行为不一致
- python - Pandas:根据特定列值重置增量
- javascript - 循环遍历一个javascript数组将值添加到另一个数组
- rabbitmq - 如何使用 Apache Camel 在 RabbitMQ 消息上设置自定义标头?
- java - Spring Boot @GetMapping 到以 .jsp 结尾的 URL
- python - XPath 总是返回一个空列表
- python - 无法通过代理链运行 selenium python 脚本
- sql - 基于同一视图中的列添加其他列并放置值