首页 > 解决方案 > 如何使用php返回ajax

问题描述

我有一个关于如何php使用 ajax 在 jquery 中返回的问题。

我有 html 字段:

<input type='text' id='name'>
<input type='text' id='color'>
<input type='text' id='material'>

我将它的值发送到 php 以检查它是否存在

在php中我有如果将错误号写入数组$errors:

if($_POST['name'] == "") { $errors[] = "1"; }

if($_POST['name'] == "Name") { $errors[] = "2"; }

最后 php 返回带有错误的数组:

foreach($errors AS $error) {
                echo $error";
            }

现在,当我收到错误时,我想对 css 进行更改。像这样的东西

success: function(html){
    if(html.$errors.1) {do this}  //this is not correct js I know, but please understand me, I am just learning

          if(html.$errors.2) {do this}
                }

问题是我不知道如何访问错误;html 返回类似这样的内容:123 如果例如第二个字段没有错误,则返回:13

你们能帮我解决这种情况吗?

先感谢您!

标签: phpjqueryhtmlajaxweb

解决方案


尝试这样的事情

<input type='text' id='name'>
<span id="name_err" style="display:none;">Please enter name</span>

<input type='text' id='color'> 
<span id="color_err" style="display:none;">Please enter color</span>

<input type='text' id='material'>
<span id="material_err" style="display:none;">Please enter material</span>

在Javascript中,这样写

if(html.$errors.2)
{
document.getElementById("color").style.display = "block"; 
}
 if(html.$errors.1)
{
document.getElementById("name").style.display = "block"; 
}
 if(html.$errors.3)
{
document.getElementById("material").style.display = "block"; 
}

推荐阅读