【问题标题】:AJAX not parsing data in PHPAJAX 不解析 PHP 中的数据
【发布时间】:2016-04-17 01:11:58
【问题描述】:

我在通过 Ajax 将一个简单的表单字段数据发送到另一个 PHP 文件时遇到了一个意外问题。我已经做了很多次了,但这次我不知道我做错了什么。

请帮忙!

这是我的表格:

<form action="textify.php" method="post">
    <input type="text" name="textify">
    <button>textify it!</button>
    <pre style="display: none;"></pre>
</form>

这是我的带有 AJAX 的 jQuery:

$(document).ready(function(){
     $('form').submit(function(){

         var textify = $('input[name=textify]').val();

         $.post('textify.php', {data: textify}, function(txt){
             $('pre').show();
             $('pre').text(txt);
         });

         return false;
     });
});

这是我将数据发送到的文件(textify.php)

class textify
{
    function __construct() {
        $textify = $_POST['data'];
        echo $textify;
    }
}
new textify;

这是出乎意料的问题:

<br /><b>Notice</b>:  Undefined index: data in <b>C:\Users\omer\Desktop\textify\textify.php</b> on line <b>19</b><br />

【问题讨论】:

  • 太棒了!那么意外的问题是什么?
  • 你必须使用$_REQUEST['data']; 而不是$_REQUEST['text']
  • @Omer 那么请更新问题,因为$_POST['data'] 不能产生Undefined index: text 作为错误,所以在您的代码中没有任何文本作为索引。
  • 哈哈,为所有人免费投票:D
  • 你正在使用$.post,但你没有使用event.preventDefault()虽然有submitevent

标签: php jquery ajax oop


【解决方案1】:

只需更改{text: textify} 而不是{data: textify},如下所示:

$(document).ready(function(){
     $('form').submit(function(){

         var textify = $('input[name="textify"]').val();

         $.post('textify.php', {text: textify}, function(txt){
             $('pre').show();
             $('pre').text(txt);
         });

         return false;
     });
});

【讨论】:

  • 你能再看看我的问题吗...我做了一些改变
【解决方案2】:

错误很简单,键名无效。您使用键名data,但您得到不存在的text

改变

 $.post('textify.php', {data: textify}, function(txt){

 $.post('textify.php', {text: textify}, function(txt){

或者更好地使用serialize()来避免此类错误。

编辑:

将代码更改为:

 $(document).ready(function(){
     $('form').submit(function(ev){
         ev.preventDefault();
         $.post('textify.php', $(this).serialize(), function(txt){
             $('pre').show();
             $('pre').text(txt);
         });
     });
});

在 PHP 中

echo $_POST['textify'];

【讨论】:

  • 谢谢罗伯特......你的答案真的很好,但问题是我的代码也很好:)我没有使用任何本地服务器来测试它......我使用的是 phpStorm 自己的 php 编译器这导致了这个问题。刚刚将我的项目移动到 XAMPP htdocs 并且我的代码工作了:)...但是感谢您的努力
【解决方案3】:

使用 $_REQUEST['data'] 代替 $_REQUEST['text']

class textify

{
    function __construct()
    {
        $textify = $_REQUEST['data']; //change text to data because you use data in ajax post.

        echo $textify;

    }
}


new textify;

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2016-02-07
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2013-07-08
    相关资源
    最近更新 更多