Я нигде не смог найти ответ на этот вопрос.У меня есть обработчик события click для кнопки отправки формы, которая отправляет JSON в php-файл, который обрабатывает ввод и возвращает результат XML.Он отлично работал, когда я использовал $ .post () для этого, но мне нужно было иметь дополнительный обработчик ошибок в случае проблем с соединением или сервером.Поэтому я обратился к методу $ .ajax () со встроенным обратным вызовом ошибок, и он ни разу не работал.Я продолжаю получать http 200 с "parsererror".Я пробовал возиться с 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;
?>
Любая помощь будет принята с благодарностью.Я нахожусь в конце своей веревки.
Спасибо
Да, верно, Слайфти, я сразу бросил слишком много, но в то время я был вне разочарования.
Я пытался загрузить firebug, но это не удалось по буквально неизвестной причине.Никогда не использовал его раньше и думал, что он придет, как вы сказали.
Я запустил скрипт processForm.php как обычную php-страницу с фиктивными данными, и она работает плавно.Он также работает плавно в сочетании с обработчиком кликов, получающим свои данные через $.post()
.Когда я заменяю $.post()
на $.ajax()
, чтобы воспользоваться функцией обратного вызова с ошибкой в случае проблем с сервером / соединением, она вообще не работает.Обратный вызов ошибки всегда срабатывает и выдает http 200
и "parsererror."
. Когда я смотрю на строку запроса, когда мой класс базы данных выполняет запрос, он пытается вставить '0'
в базу данных.Так или иначе, похоже, что $.ajax
не отправляет данные JSON.Я попытался повозиться с contenType до 'application/json'
и перепробовал много вещей, но, похоже, ничего не работает.Я не вижу никаких синтаксических ошибок.Почти интересно, нужно ли мне просто вернуться к использованию $.post()
и использованию (я думаю, это называется) .ajaxError()
и запустить его, если есть проблемы с сервером / connectx, которые необходимо решить.