简体   繁体   English

如何从成功中获取ajax响应并使用jQuery将其分配给变量?

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

Hello guys I have a problem in getting the response from my ajax. 大家好我从ajax得到回复有问题。 If I display it in the console. 如果我在控制台中显示它。 I can view it. 我可以看到它。 But How do I assign it in a variable? 但是如何在变量中分配它?

Here's what I have. 这就是我所拥有的。 In my PHP code I have this 在我的PHP代码中,我有这个

public function checkPassword($password){

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

            echo $validate;

}

In my jquery I have this 在我的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 is in response variable of success function. response是成功函数的响应变量。

indexof returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, returns -1 if the value is not found . indexof返回指定值第一次出现的调用String对象内的索引,从fromIndex开始搜索, 如果找不到该值则返回-1

try something like this 尝试这样的事情

   <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>

In your success response you will get what you are set to output in php. 在您的成功响应中,您将获得在php中输出的内容。 If you want to get an array or data set you can encode it in json in your php script like 如果你想获得一个数组或数据集,你可以在你的php脚本中用json编码它

echo json_encode($validate);

Then in your jquery you can use this response like this 然后在你的jquery中你可以像这样使用这个响应

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

console.log will print json object in browser console. console.log将在浏览器控制台中打印json对象。 You can use this json object like this 你可以像这样使用这个json对象

responseData.some_data

Ajax is asynch so you will have access to it after the ajax method returns: 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;

            }

        });

Your response data is in response variable of success function. 您的响应数据是成功函数的response变量。 Since the response type is json you can assign it directly to javaScript variable. 由于响应类型是json,因此可以将其直接分配给javaScript变量。

Also you comparison is wrong try if(g == '1') instead if(g == 1) . 你也比较错误尝试if(g == '1')而不是if(g == 1) You are getting a string as response and your checking equality with a numeric type which won't be equal at any point. 你得到一个字符串作为响应和你的检查相等与数字类型在任何点都不相等。

ie:- 即: -

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

if your json response is as shown below 如果您的json响应如下所示

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

you can access menuitem array as 你可以访问menuitem数组

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

response parameter itself contain data so just assign that to variable and use it. 响应参数本身包含数据,因此只需将其分配给变量并使用它。

 $.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;
      }
    }
  });
});

File Name votepost.php 文件名称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 reponse use $.trim for IF ELSE 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');
        }
    });

I hope you will solve your problem 我希望你能解决你的问题

You can create the js blank array and assign it to the same array. 您可以创建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