从PHP到javascript的JSON

问题描述:

I received a array in json. How can I get values with bucle for in javascript?. If array json hasn't assign a variable name

I have a array in php which convert to json

 echo json_encode($error);

I get the json following:

json image

values in json

["El nombre del usuario no puede estar vacio","La contrase\u00f1a debe tener un m\u00ednimo de
 7 caracteres"]

How can I get data in javascript my function ajax

      function submitForm()
        {
            var dataString = $("#userForm").serialize();
            console.log(dataString);
            $.ajax({
                type: "POST",
                url: "/altausers",
                data: dataString,
                success: function(text)
                {
                   if(text==='success')
                   {

                   }
                   else
                   {
                       $("#error").removeClass('hidden'); 
#get values json here



                   }
                }
            });

    }

我在json中收到了一个数组。 如何在javascript中使用bucle获取值?。 如果数组json没有分配变量名 p>

我在php中有一个转换为json的数组 p>

  echo json_encode($ error); 
  code>  pre> 
 
 

我得到以下json: p>

p>

json中的值 p>

  [“El nombre del usuario no puede estar vacio”,“  La contrase \ u00f1a debe tener un m \ u00ednimo de 
 7 caracteres“] 
  code>  pre> 
 
 

如何在javascript中获取数据我的函数ajax p>

  function submitForm()
 {
 var dataString = $(“#userForm”)。serialize(); 
 console.log(dataString); 
 $ .ajax({
 键入:“POST”,
 url:“/ altausers”,
 data:dataString,
 success:function(text)
 {
 if(text ==='success')
  {
 
} 
其他
 {
 $(“#error”)。removeClass('hidden');  
#在这里获取值json 
 
 
 
} 
} 
} 
}); 
 
} 
  code>  pre> 
  div>

You would have to specify

dataType: 'json'

then, your data would be in a javascript array:

function submitForm()
    {
        var dataString = $("#userForm").serialize();
        console.log(dataString);
        $.ajax({
            type: "POST",
            url: "/altausers",
            data: dataString,
            dataType: 'json',
            success: function(text)
            {
               if(text.length > 0) {
               $.each(text,function(index,value) {
                    alert('Response: '+ value);
               }

            }
        });

}

However, you would have to make sure that php ALWAYS returns a json-encoded response... even if you do it manually like:

<?php echo "[success]"; ?>

In javascript, you would just test

if(text[0] == 'success') { //hurray!!
}

PHP has method known as json_encode and json_decode which can me used to handle json data in php, while the json data can be directly accessed in javascript so I think you should look into that