jQuery AJAX/POST未将数据发送到PHP [英] jQuery AJAX/POST not sending data to PHP

查看:105
本文介绍了jQuery AJAX/POST未将数据发送到PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我现在有一段时间这个问题了,我知道这个主题上有无数的问题,相信我我尝试了所有可能的解决方案,但仍然行不通.

这是最简单的示例,在我看来,该示例不起作用

jQuery:

$.ajax({
    url: "ajax/add-user.php",
    type: "POST",
    data: {name: 'John'},
    success: function(data){
        console.log(data);
    }
});

PHP

echo json_encode($_POST);

就是这样. 我总是得到一个空数组作为回应.我尝试将serialize()用于data:,但响应始终为空.我什么也没收到,只有当我应该得到发布的值时才是一个空数组.

例如,如果在php中,我尝试echo一些硬编码的变量来获取它们,但$_POST$_GET不起作用.

我如何识别问题的任何解决方案或方法?

谢谢.

编辑/解决方案

好,所以似乎问题出在.htaccess上,它重写了URL并删除了扩展名.实际上,在网络"标签中,请求已永久移动.从ajax网址中删除.php扩展名:已解决.谢谢您,很抱歉浪费您的时间.干杯

解决方案

您需要在ajax调用中将数据类型设置为json.

JQUERY代码:

$.ajax({
  url: "ajax/add-user.php",
  type: "POST",
  dataType:'json',
  data: {name: 'John'},
  success: function(data){
      console.log(data);
  }
});

同时验证您的后端代码(php),是否可以接受json数据?

如果没有,请按如下所示配置标题:

PHP代码:

/**
 * Send as JSON
 */
header("Content-Type: application/json", true);

快乐编码:

So I have this problem for a while now, and I know there are countless questions on this topic, believe me I tried every solution possible but still does not work.

This is the simplest of examples which in my case is not working

jQuery:

$.ajax({
    url: "ajax/add-user.php",
    type: "POST",
    data: {name: 'John'},
    success: function(data){
        console.log(data);
    }
});

PHP

echo json_encode($_POST);

That's it. I always get back an empty array as a response. I tried with serialize() for the data: but the response is always empty. I get no errors whatsoever, just an empty array when I should get the posted values.

If, for example, in php I try to echo some hard-coded variables I get them, but the $_POST and $_GET don't work.

Any solution or methods of how I can identify the problem ?

Thank you.

EDIT/SOLUTION

Ok, so it seems the problem was with .htaccess which rewrites the url and removes the extension. In the network tab indeed the request was moved permanently. Removing the .php extension from the ajax url: solved it. Thank you and sorry for wasting time. Cheers

解决方案

You need to set the data type as json in ajax call.

JQUERY CODE:

$.ajax({
  url: "ajax/add-user.php",
  type: "POST",
  dataType:'json',
  data: {name: 'John'},
  success: function(data){
      console.log(data);
  }
});

At the same time verify your backend code(php), whether it can accept json data ?

If not, configure the header as below:

PHP CODE:

/**
 * Send as JSON
 */
header("Content-Type: application/json", true);

Happy Coding :

这篇关于jQuery AJAX/POST未将数据发送到PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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