doudou1438 2016-02-23 11:30
浏览 24
已采纳

从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



                   }
                }
            });

    }
  • 写回答

2条回答 默认 最新

  • dtewnsdf47253 2016-02-24 08:48
    关注

    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!!
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?