---
title: "使用ajax的经典错误"
author: "新来的菜鸟"
date: "2010-12-18T01:37:55Z"
tags: ["Ajax"]
categories: ["Web前端"]
slug: "ajax"
draft: false
lastmod: "2010-12-18T01:37:55Z"
id: 846077
url: "https://jianghuguke.iteye.com/blog/846077"
---

在使用ajax时，出现的经典错误，切记ajax是异步的，程序不会等待其异步返回值，不然就是同步的了。

 

 

 

function test(){

  var result=chk\_str();

  alert(result);  //此处的返回值一般是undefined，因为ajax是异步的，在调用chk\_str()时，开始执行$.post()时，该程序就执行过了，开始后续出来，不会等待$.post()的返回值，所以此时抓到的返回值result为undefined。

    ……

 

 

function chk\_str(){

   var  returnflag="ok";

   $.post(someUrl,function(data){                  

                  if($.trim(data='')){

                       return  returnflag;      

                      }else{

                        returnflag=data;

                        return  returnflag;

                     }             

              });

 

}