有条件的if语句在AJAX发布后使用响应,这样可以吗


Conditional if statement after AJAX post using response, is this ok?

我使用的带有单个输入的表单使用AJAX发布到服务器。我计划获取输入的值,它是一个字符串,并检查数据库中是否已经存在该字符串。我将使用in_array(),如果字符串不存在,则将其插入数据库,如果重复,则回显1或0,结果返回1或0。

在我的AJAX中,我在成功时使用这个简单的函数,如果结果返回1,我将使用jQuery显示成功消息,否则我将显示错误并退出。这是一个验证服务器端而不通过返回1或0和exit();来提交表单的好方法吗?

    success: function(result)
    {
      if(result == 1)
    { string was inserted to db }
    else
    { 
duplicate exists 
      exit();
      }

感谢

我会亲自做的,所以在php中,我返回一个json编码的标识数组,其中包含一些关于响应的信息。为了调试和将来可能的更改,我通常会包含比需要更多的信息。

if($results >= 1){
    $duplicate_exists = 'true';
}elseif($results < 1){
    $duplicate_exists = 'false';
};
$result = array(
    'exists' => $duplicate_exists ,
    'status' => $status,
    'time' => time()
    // etc
);
echo  json_encode($result)

然后将json解码为javascript中的对象:

success: function(result){
    result = jQuery.parseJSON(result)
// you can also use eval(result) , but it's much slower.
    if(result.exists == 'false'){
        // string was inserted to db
    }else{ 
        // duplicate exists 
        exit();
    }

您可以使用以下代码使用AJAXJS发布和检索结果。

$.ajax({
        url: 'https://api.github.com/gists',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(data)
      })
      .success( function(e) {
       res = jQuery.parseJSON(e);
       if(res.exists == 'false'){
        // string was inserted to db
       }
       else if(res.exists == 'true'){ 
        // duplicate exists 
        exit();
      }

      })
      .error( function(e) {
        //there was error
      });