当我在php上获得echo success
时,我遇到了ajax的一个问题。如果
if(text[0]==="success")
php内的代码
if(count($error)==0)
{
$user = ORM::for_table('usuario')->create();
$user->username = $username;
$user->contrasenia = password_hash($password, PASSWORD_DEFAULT);
$user->email = $email;
$user->admin = $is_admin;
$user->save();
echo "success";
}
else
{
$error = json_encode($error);
echo $error;
}
我在ajax中的代码
[![$("#create-button").on('click', function(event){
//cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm()
{
var dataString = $("#userForm").serialize();;
$.ajax({
dataType: "json",
type: "POST",
url: "/altausers",
data: dataString,
success: function(text)
{
console.log("hola");
console.log(text);
if(text\[0\]==="success")
{
alert("hola");
//$("#error").addClass('hidden');
}
else if(text.length > 0)
{
$("#error").removeClass('hidden');
texterror = "<ol type='disc'>";
$.each(text,function(index,value)
{
texterror+="<li>"+value+"</li>";
});
texterror+="</ol>";
document.getElementById("error").innerHTML = texterror;
}
}
});
}
图像控制台
有什么问题?
能说我哪个有问题吗?
我已将消息成功转换为json
答案 0 :(得分:0)
用
替换成功回音 echo json_encode(["success"]);
或保留echo相同,并在ajax中替换
if(text == "success")
答案 1 :(得分:0)
问题可能是它是一个数组,所以你可以试试这个:
$.ajax({
url: "items.php",
async: false,
type: "POST",
dataType: "JSON",
data: { "command" : "getItems" }
}).success(function( response ) {
alert( response.fruits.apple );
alert(Object.keys(response).length);
});
如果你想看到结果:
Object.keys( response ).forEach(function( key ) {
console.log('key name: ', key);
console.log('value: ', response[key]);
});