jquery ajax get 获取返回值是undefined解决方案jquery ajax get 获取返回值是undefined解决方案

jquery ajax get 获取返回值是undefined解决方案

正常情况下,由于jquery的 .ajax() . a j a x ( ) 、 .post()和$.get()方法获取到的数据若想返回给js函数,会发现返回值是undefined,这是由于ajax默认是异步请求数据的,换句话说,你想获取的变量值还在请求中,这时候你读取这个变量值就只能是undefined了,所以需要加入一行async:false,要求ajax是同步执行。如下例程:

//ajax获取数据
function smsverify(){
    var check_res;
    var ajaxurl = APP_ROOT+"/index.php";
    var query = new Object();
    $.ajax({ 
        async:false,
        url: ajaxurl,
        data:query,
        type: "POST",
        dataType: "json",
        success: function(result){
            check_res=result;
        },error:function(){}
    });
    return check_res;    
}

核心是加入 async:false,如果你没有加入这一行,你会发现函数返回的undefined

async作用

async. 默认是 true,即为异步方式,$.ajax执行后,会继续执行ajax后面的脚本,直到服务器端返回数据后,触发$.ajax里的success方法,这时候执行的是两个线程。

async 设置为 false,则所有的请求均为同步请求,在没有返回值之前,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。

参考:https://www.cnblogs.com/hnbiao/p/6208277.html

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
jQuery本身并没有提供获取设备唯一编号的方法,但是可以通过一些第三方库和浏览器API实现。以下是几种常用的方法: 1. 使用Fingerprint.js获取设备指纹 Fingerprint.js是一个开源的库,可以通过收集浏览器特征来生成一个唯一的设备指纹。可以通过以下代码引入该库并获取设备指纹: ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/fingerprintjs2/2.1.0/fingerprint2.min.js"></script> <script> new Fingerprint2().get(function(result){ console.log(result); // 输出设备指纹 }); </script> ``` 2. 使用Web API获取设备ID 浏览器提供了一些API可以获取设备ID,如DeviceMotionEvent、DeviceOrientationEvent和MediaDevices等。可以通过以下代码获取设备ID: ``` if (typeof devicePixelRatio !== 'undefined') { console.log(devicePixelRatio); // 输出设备ID } ``` 3. 自己生成设备ID 如果以上方法无法满足需求,可以自己生成一个唯一的设备ID。可以通过一些浏览器API和用户信息生成一个唯一的字符串,如以下代码: ``` var uniqueId = ''; if (typeof navigator !== 'undefined') { uniqueId += navigator.userAgent || ''; uniqueId += navigator.plugins.length || ''; uniqueId += navigator.mimeTypes.length || ''; } if (typeof screen !== 'undefined') { uniqueId += screen.width || ''; uniqueId += screen.height || ''; uniqueId += screen.availWidth || ''; uniqueId += screen.availHeight || ''; uniqueId += screen.colorDepth || ''; uniqueId += screen.pixelDepth || ''; } if (typeof window !== 'undefined' && typeof window.location !== 'undefined') { uniqueId += window.location.href || ''; uniqueId += window.location.hostname || ''; uniqueId += window.location.pathname || ''; } console.log(uniqueId); // 输出设备ID ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值