所以,我是 javascript/jquery 的新手,但我已经使用 PHP 足够长的时间了。我知道如何使用 PHP 从输入中获取数据,这非常简单,但是当尝试使用 jQuery 执行相同操作时,如何操作就在我的脑海中飘过。
现在我有这个脚本:
<script type="text/javascript">
function onSubmit( form ){
var data = JSON.stringify( $(form).serializeArray() );
console.log( data );
}
</script>
这个表格:
<form onsubmit='return onSubmit(this)'>
<input type="date"/><br/>
<input type="date"/><br/>
<input type="submit" name=""/>
</form>
我看到它很好地记录了 .json 文件 ([{"name":"from","value":"1994-01-01"},{"name":"to","值":"1994-02-02"}]
) 。我的猜测是,它几乎是将 .json 发送到 .php 文件,然后执行 $_POST,但我不知道如何从这里继续或执行它。我不知道 ajax 是否必要,如果不需要,如何在没有它的情况下做到这一点(我在这里发现的所有内容都在使用 ajax)。
最佳答案
您可以使用标准 URL 编码表示法将表单数据作为文本字符串发送,或者使用 jQuery.serialize()
作为 JSON
字符串发送。
<form id="set-date-form">
<input name="from" type="date"/><br/>
<input name="to" type="date"/><br/>
<input type="submit" id="set-date"/>
</form>
使用jQuery
<script>
$('#set-date').on('click', function (e) {
e.preventDefault();
var data = $('#set-date-form').serialize();
$.post('somephpfile.php', data, function (response) {
// response is the data echoed from php
var result = JSON.parse(response) // assuming that php echoed ['success' => true/false];
if (result.success == true) {
alert("the values were sent to db successfully");
}else {
alert("the values were not sent to db successfully");
}
})
})
</script>
然后在您的 PHP
文件中
<?php
$from = $_POST['from'];
$to = $_POST['to'];
// here you can update the database with this values
// after updating db or insert
// check if the query was successful
// if query was successful [echo json_encode(['success' => true]);] this value will be sent to javascript as a response
// if query was not successful [echo json_encode(['success' => false]);] this value will be sent to javascript as a response
关于javascript - 无需 AJAX 将 JSON 文件从 jQuery 发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43366068/