簡體   English   中英

如何從成功中獲取ajax響應並使用jQuery將其分配給變量?

[英]How to get the ajax response from success and assign it in a variable using jQuery?

大家好我從ajax得到回復有問題。 如果我在控制台中顯示它。 我可以看到它。 但是如何在變量中分配它?

這就是我所擁有的。 在我的PHP代碼中,我有這個

public function checkPassword($password){

            $username = $this->session->userdata('username');
            $validate = $this->members_model->checkPassword($password,$username);

            echo $validate;

}

在我的jquery中我有這個

$('#existing').on('keyup',function(){

            var id = '<?php echo $this->session->userdata("user_id"); ?>';
            var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';

            $.ajax({
                type: 'POST',
                url: password_url,
                data: '',
                dataType: 'json',
                success: function(response){

                var g = response;
                if(g == 1){
                    $('#existing_info').html('Password is VALID'); //Doesn't display the VALID if the response is 1. Why?
                }else{
                    $('#existing_info').html('Password is INVALID!');
                }

                }

            });

        });
$.ajax({
        type: 'POST',
        url: password_url,
        data: '',
        dataType: 'json',
        success: function(response){
           var k=response;

           if(k.indexOf("1") != -1)
             $('#existing_info').html('Password is VALID');
           else
              $('#existing_info').html('Password is INVALID!');
        }
    });

response是成功函數的響應變量。

indexof返回指定值第一次出現的調用String對象內的索引,從fromIndex開始搜索, 如果找不到該值則返回-1

嘗試這樣的事情

   <script>
        var k = null;
        $(function(){
            $('#existing').on('keyup',function(){
                var id = '<?php echo $this->session->userdata("user_id"); ?>';
                var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';

                $.ajax({
                    type: 'POST',
                    url: password_url,
                    data: '',
                    dataType: 'json',
                    success: function(response){
                        if(response == 1){
                            k = response;
                        }
                    }

                });

            });
        })
   </script>

在您的成功響應中,您將獲得在php中輸出的內容。 如果你想獲得一個數組或數據集,你可以在你的php腳本中用json編碼它

echo json_encode($validate);

然后在你的jquery中你可以像這樣使用這個響應

var responseData = jQuery.parseJSON(response);
console.log(responseData);

console.log將在瀏覽器控制台中打印json對象。 你可以像這樣使用這個json對象

responseData.some_data

Ajax是異步的,所以你可以在ajax方法返回后訪問它:

$('#existing').on('keyup',function(){

            var id = '<?php echo $this->session->userdata("user_id"); ?>';
            var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';

            $.ajax({
                type: 'POST',
                url: password_url,
                data: '',
                dataType: 'json'
            }).then(function(response){
              var k;
              if(response == 1){
                k = response;
                //call another function that needs k here
              }
            });
        });
 $.ajax({
            type: 'POST',
            url: password_url,
            data: '',
            dataType: 'json',
            success: function(response){

               k=response;

            }

        });

您的響應數據是成功函數的response變量。 由於響應類型是json,因此可以將其直接分配給javaScript變量。

你也比較錯誤嘗試if(g == '1')而不是if(g == 1) 你得到一個字符串作為響應和你的檢查相等與數字類型在任何點都不相等。

即: -

$.ajax({
                type: 'POST',
                url: password_url,
                data: '',
                dataType: 'json',
                contentType:"application/json",// Add Content type too
                success: function(response){
                    k=response;
                  }
        });

如果您的json響應如下所示

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

你可以訪問menuitem數組

success: function(response){
               k=response.menu.popup.menuitem;
            }

響應參數本身包含數據,因此只需將其分配給變量並使用它。

 $.ajax({
        type: 'POST',
        url: password_url,
        success: function(response){
         if(parseInt(response) == 1){ 
          var k = response;
          }
        }
    });
var k = null;

$('#existing').on('keyup', function() {
  var id           = '<?php echo $this->session->userdata("user_id"); ?>',
      password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';

  $.ajax({
    type    : 'POST',
    url     : password_url,
    success : function(data) {
      if(data === '1') {
        k = data;
      }
    }
  });
});

文件名稱votepost.php

<?php
include("domain.php");

$csid=$_POST['CSID'];
$voteid=$_POST['VOTEID'];
$myid=$_POST['MYID'];
$usertype=$_POST['USERTYPE'];


$myurl =URL."putvote.php?csid=".$csid."&voterid=".$myid."&voteid=".$voteid."&usertype=".$usertype;
$myurl=str_replace(" ","%20",$myurl);
$jsondata = file_get_contents($myurl);
$data = json_decode($jsondata);

if($data->response=="true")
{
    echo 'true';

}
else
{
    echo 'false';

}


?>

ajax響應使用$ .trim作為IF ELSE

$.post("votepost.php", {CSID:csid,VOTEID:voteid,MYID:myid,USERTYPE:usertype}, function (data) {

        if($.trim(data)=='true')
        {
            alert('ok');
        }
        else
        {
            alert('error');
        }
    });

我希望你能解決你的問題

您可以創建js空白數組並將其分配給同一個數組。

var resp = [];
    jQuery.ajax({
            dataType: "json",
            method: 'post',
            url: 'ajax.php',
            async: false,
            data: {postData: 'postData'},
            success: function(data){
                resp.push(data);
            }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM