将值对从jQuery发布到php文件并将数据保存在数据库中 [英] Post value pairs from jQuery to php file and save data in database

查看:80
本文介绍了将值对从jQuery发布到php文件并将数据保存在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个html文本输入字段和两个按钮.

I have two html text input fields and two buttons.

第一个按钮将来自两个输入字段的值对保存在数组中. 第二个按钮将该带有所有输入值对的数组发送到php文件,并且php文件将所有这些值保存在数据库中. 用户可以输入尽可能多的值,没有限制.

The first button saves the value pairs from the two input fields in an array. The second button sends this array with all the input value pairs to a php file and the php file saves all these values in a database. The user can input values so much as he can, there is no limit.

<input type="text" id="field1" name="field1" />
<input type="text" id="field2" name="field2" />
<button id="notizeValues">Notize</button>
<button id="sendToServer">Save</button>

我的问题是,服务器如何访问此数据? 我正在尝试:

My question is, how can the server access this data? I am trying this:

var values = [];
$('#notizeValues').click(function (){
   var value1 = $('#field1').val();
   var value2 = $('#field2').val();
   values.push({'value1': value1 , 'value2': value2 });   
});

$('#sendToServer').click(function (){
    var sendValues = values;
    $.post("achieveAdminAktion.php",{values:  sendValues },  function(data){
    $("#serverResponse").html(data);
});
});

现在出现了php文件的代码,但是我得到了整个时间的错误. 对于此解决方案,我收到警告:json_decode() expects parameter 1 to be string, array given 和回声函数中的错误:

Now comes the code of the php file, but I get the whole time errors. For this solution I get an Warning: json_decode() expects parameter 1 to be string, array given and errors in echo function:

isset($_POST['values']){
    $values = json_decode($_POST['values'], true);

     foreach ($values as $json) {
         ....save value in database....
 }
    echo $values; // nothing
}

那只是我尝试过的许多例子中的一个例子,但没有任何效果. 我怎么解决这个问题? 如何访问php文件中的这些数据,以及如何遍历json-array并将所有这些值对保存在数据库中.

That is only one example of lot of examples I tried but nothing works. How can I solve this problem? How can I access these data in php file and how can I walk through the json-array and save al these value pairs in database.

推荐答案

$.post()不会对发送到服务器的变量进行JSON编码-因此,PHP中的json_decode调用是不必要的.

$.post() doesn't JSON-encode variables sent to the server - so the json_decode call in PHP is unnecessary.

这篇关于将值对从jQuery发布到php文件并将数据保存在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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