我正在创建登录页面,我需要从api获取一些数据。我已经设置了api.php,但是我无法从表单向api.php发送一个值
我尝试了很多事情,但是我从来没有在我的php中得到这个帖子。
<script>
$(function(){
$('#forma').on('submit', function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: 'POST', // <-- get method of form
url: 'api.php', // <-- get action of form
data: {'Usernami': $("#Username").val()}, // <-- serialize all fields into a string that is ready to be posted to your PHP file
success: function(data){
alert(data);
}
});
});
});
</script>
<form method="post" id="forma">
<div class="form-group text-center">
<label for="Username"> <h1 style="color: white;"> Username:</h1></label>
<input type="texarea" name="usernami" class=" border border-white form-control" id="Username" placeholder="Enter Your Username..." required>
<label for="Username"> <h1 style="color: white;"> <br>Use Proxy: <br> </h1></label>
<center>
<input type="checkbox" id="on-off-switch" name="switch1" checked>
</center>
<br>
<button id="butoni" type="submit" class="btn btn-warning">Connect Account
</button>
</form>
<?php
print_r($_POST);
?>
答案 0 :(得分:0)
我创建了一个测试api.php文件,在其中我只是转储了$ _POST并将您的脚本标签移到body标签的末尾,对我有用。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form method="post" id="forma">
<div class="form-group text-center">
<label for="Username"> <h1 style="color: white;"> Username:</h1></label>
<input type="texarea" name="usernami" class=" border border-white form-control" id="Username" placeholder="Enter Your Username..." required>
<label for="Username"> <h1 style="color: white;"> <br>Use Proxy: <br> </h1></label>
<center>
<input type="checkbox" id="on-off-switch" name="switch1" checked>
</center>
<br>
<button id="butoni" type="submit" class="btn btn-warning">Connect Account
</button>
</form>
<script>
$(function(){
$('#forma').on('submit', function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: 'POST', // <-- get method of form
url: 'api.php', // <-- get action of form
data: {'Usernami': $("#Username").val()}, // <-- serialize all fields into a string that is ready to be posted to your PHP file
success: function(data){
alert(data);
}
});
});
});
</script>
</body>
<?php
print_r($_POST);
?>
</html>
答案 1 :(得分:0)
这就是我的方法。看起来很粗糙,但这对我来说是一个保证...
$.post(
'url',
{
'Usernami': $("#Username").val()
},
// function to handle the response
function(data,status,xhr){
console.log(data);
}
});
希望它能解决。
答案 2 :(得分:0)
据我从您的示例中看到的,您的源代码没有任何问题,但这可能是浏览器在缓存先前的脚本或页面时出现问题,您可以禁用此代码并重试,但是测试API响应的最佳方法是使用诸如POSTMAN或失眠之类的工具
我发现的唯一小问题就是这里的一个小错字
<input type="texarea" name="usernami" class=" border border-white form-control" id="Username" placeholder="Enter Your Username..." required>
我只是将其更改为键入文字
<input type="text" name="usernami" class=" border border-white form-control" id="Username" placeholder="Enter Your Username..." required>
我建议尝试在失眠状态下测试您的API,here
以下是该工具的结果