【问题标题】:How to evaluate json response data - ajax form?如何评估 json 响应数据 - ajax 形式?
【发布时间】:2017-09-08 13:04:10
【问题描述】:

我不知道如何写一个正确的问题。但请让我解释一下。我用ajax发送并用json返回。每个 json 值都包含其状态。所以我需要测试/评估状态并对其进行处理。

JSON

{url:"error",email:"ok",name:"ok"}

JS

//new port
$('#pflBtn').on('click',function(e){
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: 'inc/wcont8_port_db.php',
        data :$(this).closest('form').serialize(),
        dataType: 'json',
        success: function(data){
            if(data.url=="err"){//if url=error
                $('#plf_url').addClass('error');//will add .error into #plf_url class
            }else{
                $('#plf_url').addClass('success');
            }
        }
    })//ajax
})

html

<form class="pflForm">
    <div class="form-group form-float">         
        <div class="form-line" id="pfl_url">
            <input type="text" class="form-control" name="pfl_url" value="URL" required />
            <label class="form-label">URL (www.domain.com)</label>
        </div>
    </div><!-- form-group form-float -->
<button type="submit" id="pflBtn">Save</button>
</form>

【问题讨论】:

  • 有什么问题?
  • 您对代码有什么具体问题吗?您的描述仅说明了它的作用。虽然请注意 data.url == 'err' 应该是 data.url == 'error' 给定您的对象。
  • JSON 名称不应该用双引号括起来吗?
  • @yezzz 是的,虽然这看起来像 JSON 响应产生的反序列化对象,它不需要引用键
  • 感谢这里的一切努力,我解决了这个问题。

标签: javascript php jquery json ajax


【解决方案1】:

你犯了两个错误,用代码检查我的cmets并通过更改它们重试:

$('#pflBtn').on('click',function(e){
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: 'inc/wcont8_port_db.php',
        data :$(this).closest('form').serialize(),
        dataType: 'json',
        success: function(data){
            if(data.url=="error"){// url has value 'error', but this was checking 'err'
                $('#plf_url').addClass('error');//will add .error into #plf_url class but the class is not available in your html,
            }else{
                $('#plf_url').addClass('success');
            }
        }
    })//ajax
})

【讨论】:

  • 我希望当 data.url="error" 它会添加行
    与类 .error 里面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 2015-01-27
  • 2016-04-20
  • 1970-01-01
  • 2014-07-06
  • 2021-04-03
相关资源
最近更新 更多