使用$ .ajax()将JSON发送到PHP文件的问题

时间:2011-07-09 18:51:37

标签: json jquery

我无法在任何地方找到答案。我有一个表单提交按钮的单击事件处理程序,它将JSON发送到php文件,该文件处理输入并返回XML结果。当我使用$ .post()时,它工作得很好,但是如果存在连接或服务器问题,我需要一个额外的错误处理程序。所以我转向$ .ajax()方法,它内置了错误回调,它从未工作过一次。我一直收到带有“parsererror”的http 200。我已经尝试搞乱了contentType和其他参数,但没有任何作用。我把头发拉出来了。这是代码:

单击具有$ .post()的处理程序,完美运行:

      $('[id$=-submit]').click
 (
function()
{
  formName = $(this).attr('id');
  formName = formName.replace('-submit','');
  var isSubmitted = getSubmittedForms(formName);
  if(isSubmitted == 'no')
  {
    var inputJSON = {};
    inputError = 0;
    dataerror = 0;
    submitButtonText = '';
    submitButtonText = $(this).text();
    submitId = $(this).attr('id');
    if (submitButtonText == '')
    {
      $(this).attr('src', 'images/' + formName + '-loading.gif'); 
    }
    else
    {
      $(this).text('Loading');
    }
    $('input[id*='+formName+']').each
    (
      function()
      {
        currentId = $(this).attr('id');
        currentData = $(this).val();
        currentInputId = currentId.replace(formName+'-','');
        compareString = getFormInputRegex(currentInputId);
        regexResult = compareString.test($(this).val());
        if(regexResult != true)
        {
          $(this).val('');
          $('#' + currentId + '-error').show();
          inputError = 1;
          if (submitButtonText == '')
          {
            $('#' + submitId).attr('src', 'images/' + formName + '-submit.gif'); 
          }
          else
          {
            $('#' + submitId).html('<a href="#">' + submitButtonText + '</a>');
          }
        }
        else
        {
          inputJSON[currentInputId] = currentData; 
          $('#' + currentId + '-error').hide();
        }
      }
    )
    if(inputError==0)
    {
      JSONdata = JSON.stringify(inputJSON);
      $.post
      (
        'processForm.php',
        {
          data: JSONdata         
        },
        function(xmldata)
        {
          if(xmldata)
          {
            $(xmldata).find('dataerror').each
            (
              function()
              {
                dataerror = 1;
                $('#' + formName + '-submitted-message').text('An error has occurred, and your information could not be sent at this time.');
                $('#' + formName + '-submitted-message').show();
              }
            );
            if(dataerror != 1)
            {
              $(xmldata).find('inputerror').each
              (
                function()
                {
                  inputError = 1;
                  errorTagName = $(this).text();
                  $('#' + errorTagName).val('');
                  $('#' + formName + '-' + errorTagName + '-error').show();
                }
              );
              if(inputError == 0)
              {
                $('input[id*='+formName+']').each
                (
                  function()
                  {
                    $(this).val('');
                    $(this).next().hide();
                  }
                );
                $('#' + formName + '-submitted-message').show();
                submitClicked = submitClicked + formName + 'qqq';
              }
            }
            if (submitButtonText == '')
            {
              $('#' + submitId).attr('src', 'images/' + formName + '-submit.gif'); 
            }
            else
            {
              $('#' + submitId).html('<a href="#">' + submitButtonText + '</a>');
            }            
          }
        },
        "xml"
      );
    }
  }
  else
  {
    $('#' + formName + '-submitted-message').text('This form has already been submitted.');
    $('#' + formName + '-submitted-message').show();
    clearTimeout(formSubmitTimer);
    formSubmitTimer = setTimeout
    (
      function()
      {
        $('#' + formName + '-submitted-message').fadeOut('fast');
      }
      ,5000
    )
    $('input[id*='+formName+']').each
    (
      function()
      {
        $(this).val('');
        $(this).next().hide();
      }
    );
  }
}
  );

以下是使用$ .ajax()的脚本永远不会起作用:

  $('[id$=-submit]').click
  (
function()
{
  formName = $(this).attr('id');
  formName = formName.replace('-submit','');
  var isSubmitted = getSubmittedForms(formName);
  if(isSubmitted == 'no')
  {
    var inputJSON = {};
    inputError = 0;
    dataerror = 0;
    submitButtonText = '';
    submitButtonText = $(this).text();
    submitId = $(this).attr('id');
    if (submitButtonText == '')
    {
      $(this).attr('src', 'images/' + formName + '-loading.gif'); 
    }
    else
    {
      $(this).text('Loading');
    }
    $('input[id*='+formName+']').each
    (
      function()
      {
        currentId = $(this).attr('id');
        currentData = $(this).val();
        currentInputId = currentId.replace(formName+'-','');
        compareString = getFormInputRegex(currentInputId);
        regexResult = compareString.test($(this).val());
        if(regexResult != true)
        {
          $(this).val('');
          $('#' + currentId + '-error').show();
          inputError = 1;
          if (submitButtonText == '')
          {
            $('#' + submitId).attr('src', 'images/' + formName + '-submit.gif'); 
          }
          else
          {
            $('#' + submitId).html('<a href="#">' + submitButtonText + '</a>');
          }
        }
        else
        {
          inputJSON[currentInputId] = currentData; 
          $('#' + currentId + '-error').hide();
        }
      }
    )
    if(inputError==0)
    {
      JSONdata = JSON.stringify(inputJSON);
      $.ajax
      (
        {
          type: "post",
          url: "processFrom.php",
          data: JSONdata,
          dataType: "xml",
          success: function(xmldata, status, xhr)
          {
            $(xmldata).find('dataerror').each
            (
              function()
              {
                alert('Data error detected!');
                dataerror = 1;
                $('#' + formName + '-submitted-message').text('An error has occurred, and your information could not be sent at this time.');
                $('#' + formName + '-submitted-message').show();
              }
            );
            if(dataerror != 1)
            {
              $(xmldata).find('inputerror').each
              (
                function()
                {
                  inputError = 1;
                  errorTagName = $(this).text();
                  $('#' + errorTagName).val('');
                  $('#' + formName + '-' + errorTagName + '-error').show();
                }
              );
              if(inputError == 0)
              {
                $('input[id*='+formName+']').each
                (
                  function()
                  {
                    $(this).val('');
                    $(this).next().hide();
                  }
                );
                $('#' + formName + '-submitted-message').show();
                submitClicked = submitClicked + formName + 'qqq';
              }
            }
            if(submitButtonText == '')
            {
              $('#' + submitId).attr('src', 'images/' + formName + '-submit.gif'); 
            }
            else
            {
              $('#' + submitId).html('<a href="#">' + submitButtonText + '</a>');
            }            

          },
          error: function(XHRerror, textStatusError, thrownError)
          {
            alert(textStatusError);
            $('#' + formName + '-submitted-message').text('An error has occurred, and your information could not be sent at this time.');
            $('#' + formName + '-submitted-message').show();
            if(submitButtonText == '')
            {
              $('#' + submitId).attr('src', 'images/' + formName + '-submit.gif'); 
            }
            else
            {
              $('#' + submitId).html('<a href="#">' + submitButtonText + '</a>');
            }
          }
        }
      );
    }
  }
  else
  {
    $('#' + formName + '-submitted-message').text('This form has already been submitted.');
    $('#' + formName + '-submitted-message').show();
    clearTimeout(formSubmitTimer);
    formSubmitTimer = setTimeout
    (
      function()
      {
        $('#' + formName + '-submitted-message').fadeOut('fast');
      }
      ,5000
    )
    $('input[id*='+formName+']').each
    (
      function()
      {
        $(this).val('');
        $(this).next().hide();
      }
    );
  }
}
 );

这是php处理文件:

<?php
header('Cache-Control: no-cache');
header("Content-type: text/xml");
require("requirepath.php");
require(REQUIRE_PATH."constants.php");
require(REQUIRE_PATH."autoload.php");
$formData = dtbs::getDb();
function getInputRegex($idname)
{
switch($idname)
{
case 'firstname':
$regexString = '/^[a-zA-Z]+((\s|\-)[a-zA-Z]+)?$/';
case 'lastname':
$regexString = '/^[a-zA-Z]+((\s|\-)[a-zA-Z]+)?$/';
default:
$regexString = '/^[a-zA-Z]+((\s|\-)[a-zA-Z]+)?$/';
} 
return $regexString;
}
$error_number = 0;
$JSON_data = array();
$XML_response = '<'.'?xml version="1.0" encoding="iso-8859-1"?'.'><response>';
if(isset($_POST))
{
$JSON_data = json_decode($_POST['data'], true);
foreach($JSON_data as $key => $value)
{                
$match_string = getInputRegex($key);
$match_result = preg_match($match_string, $value);
if($match_result != 1)
{
$XML_response .= '<inputerror>'.$key.'</inputerror>';
$error_number = 1;
}
}
if($error_number != 1)
{
$XML_response .= '<inputsuccess>inputsuccess</inputsuccess>';
$insert_fields = '(id,';
$insert_data = '(0,';
foreach($JSON_data as $field => $data)
{
$insert_fields .= preg_replace('/[^a-z]/i', "", $field);
$insert_fields .= ',';
$insert_data .= "'$data',";
}
$insert_fields = rtrim($insert_fields, ",");
$insert_fields .= ")";
$insert_data = rtrim($insert_data, ",");
$insert_data .= ")";
$dataInsert = $formData->insert("userdata",$insert_fields,$insert_data);
if($dataInsert === 'queryError')
{
$XML_response .= '<dataerror></dataerror>';
} 
}
}
else
{
$XML_response .= '<dataerror></dataerror>';
}
$XML_response .= '</response>';
echo $XML_response;
?>

非常感谢任何帮助。我已经走到了尽头。

由于


是的,你是正确的Slifty,我确实倒了太多,但当时我已经过了挫折。

  1. 我试图加载萤火虫,但它失败了,因为字面上是一个未知的原因。从来没有使用它,并认为它会像你说的那样出现。

  2. 我确实将processForm.php脚本作为带有虚拟数据的普通php页面运行,它可以游戏运行。它还可以与点击处理程序一起游戏,通过$.post()接收数据。当我用$.post()替换$.ajax()以在服务器/连接问题时利用错误回调,它根本不起作用。错误回调总是触发并且它提供http 200"parsererror."当我查看查询字符串时,我的数据库类运行查询时它会尝试将'0'插入数据库。因此,某种程度上看起来$.ajax没有发送JSON数据。我尝试将contenType修改为'application/json'并尝试了很多东西,但似乎没有任何效果。我没有看到任何语法错误。几乎想知道我是否需要回到使用$.post()和使用(我认为它被称为).ajaxError()并解雇,如果有服务器/连接器问题需要处理。

    < / LI>

1 个答案:

答案 0 :(得分:0)

这个问题的根源是“请帮助调试!”所以我会抛出一些调试jQuery ajax问题的建议。

  • 查看firebug / chrome资源管理器中的“响应”选项卡。这将让您查看请求详细信息以及有关服务器响应的信息。你的PHP可能会在某处抛出错误。
  • 尝试通过在浏览器窗口中加载相关的PHP页面来跳过AJAX步骤,这将帮助您减少一半的复杂性并将错误隔离到客户端或服务器端。
  • 尝试以更简单的方式运行ajax。你当前的电话有很多额外的逻辑。当您使用简单的脚本调用页面时会发生什么?

注意:如果可能,请优化您的问题以删除您明确发现与错误无关的代码,这将使我们更容易提供有用的建议。例如,抛出错误在哪里?