使用AJAX在PHP帖子中使用未定义的索引 [英] Undefined index in PHP post with AJAX

查看:63
本文介绍了使用AJAX在PHP帖子中使用未定义的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的本地机器上,我正在尝试将数据从json保存到我的mysql数据库,我正在使用Wampserver。

In my local machine, I am trying to save data from a json to my mysql database, I am using Wampserver.

在我的html页面中(saveInfo.php ),我有这个jquery代码:

In my html page (saveInfo.php), I have this jquery code:

<script type="text/javascript">
            var jsObj = {"user_id":5, "login":"hsm"};
            var jsonobj = JSON.stringify(jsObj);            
            $.ajax({  
                type: "POST",  
                url: "json_handler.php",  
                data: { 'jsonobj':jsonobj },      
                success: function(){  
                  alert('success');
                  window.location = "http://localhost/quranMapping/php/json_handler.php";
                } 
            });
</script>

另一方面,我有我的服务器端php代码( json_handler .php )这样:

In the other side, I have my server-side php code (json_handler.php) like that:

<?php

$input = file_get_contents('php://input');
$input = $_POST['jsonobj'];

$result = json_decode($input);

echo $result->user_id;

?>

但是当我运行该代码时,我收到此错误:

But when I run that code, I get this error:

推荐答案

你应该删除它:

var jsonobj = JSON.stringify(jsObj); 

并更改

data: { 'jsonobj':jsonobj }, 

data: jsObj, 

在php端解码数据只需使用

On the php side to decode the data just use

$user_id = isset($_POST["user_id"])?$_POST["user_id"]:"";
$login   = isset($_POST["login"])?$_POST["login"]:"";

也没有必要这样做

$input = file_get_contents('php://input');

由于表单是以对象作为数据发布的,因此值为 application / x-www-form-urlencoded 所以它不是有效的json。

Since the form is being posted with an object as data the value will be application/x-www-form-urlencoded so it don't be valid json.

这篇关于使用AJAX在PHP帖子中使用未定义的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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