在没有AJAX的情况下将JSON文件从jQuery发送到PHP [英] Send JSON file from jQuery to PHP without AJAX

查看:85
本文介绍了在没有AJAX的情况下将JSON文件从jQuery发送到PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我是javascript / jquery的新手,但是我用PHP玩了很长时间。我知道如何使用PHP从输入中获取数据,这非常简单,但是当尝试使用jQuery执行相同操作时,如何做到这一点只是飞得很快。

So, I'm new to javascript/jquery, but I have played around long enough with PHP. I know how to get data from an input with PHP, which is really easy, but when trying to do the same with jQuery, how to do it just flies over my head.

现在我有这个脚本:

<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,value:1994-02-02}] )。我的猜测是它几乎将.json发送到.php文件,然后执行$ _POST,但我不知道如何从这里继续或者这样做。我不知道ajax是否有必要,如果不是,如果没有它,怎么办呢(我在这里找到的所有内容都是使用ajax)。

I see it logs the .json file just fine ([{"name":"from","value":"1994-01-01"},{"name":"to","value":"1994-02-02"}]) . My guess is it's pretty much sending the .json to the .php file, and then doing a $_POST, but I don't know how to proceed from here or do it. I don't know if ajax IS necessary or not, and if not, how to do it without it (everything I found around here is using ajax).

推荐答案

您可以使用标准的URL编码表示法将表单数据作为文本字符串发送,或者使用 jQuery.serialize将 JSON 作为字符串发送()

You can send form data as text string in standard URL-encoded notation or as JSON like string with jQuery.serialize().

<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

这篇关于在没有AJAX的情况下将JSON文件从jQuery发送到PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆