jQuery select2使用记录

原创
2019/02/14 17:50
阅读数 399

ajax输出数据的格式必须为:[{"id":1,"txt":"content},{"id":2,"txt":"datalist"}]


jQuery(function (){

	
	$("#data").select2({
		 ajax: {
			 url: "json.php",
			 dataType: "json",
			 delay: 250,
			 data: function (params) {
				 return {
					 query: params.term,
				 };
			 },
			 processResults: function (data) {
				return {
					results: data
				    };
			 },
			 cache: true
		 },
		 placeholder: "This is tip txt",
		 escapeMarkup: function (markup) { return markup; }, 
		 minimumInputLength: 2,
		 templateResult: formatRepo, 
		 templateSelection: formatRepoSelection
	});
		
});




function formatRepo(repo){
	if (repo.loading) {
    	return repo.text;
	}
	
	return repo.text;
}

function formatRepoSelection(repo){
	
	if (repo.loading) {
    	return repo.text;
	}
	
	return repo.text;
};

示例select2.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>select2</title>
<script src="http://libs.baidu.com/jquery/1.10.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>

<body>

<form method="post" action="json.php">

<select id="data" name="user_name" style="width:500px" ></select>

<input type="submit" value="submit_data">

</form>

<script>

jQuery(function (){

	
	$("#data").select2({
		 ajax: {
			 url: "json.php",
			 dataType: "json",
			 delay: 250,
			 data: function (params) {
				 return {
					 query: params.term,
				 };
			 },
			 processResults: function (data) {
							 return {
								 results: data
							 };
			 },
			 cache: true
		 },
		 placeholder: "请搜索一个账号",
		 escapeMarkup: function (markup) { return markup; }, 
		 minimumInputLength: 2,
		 templateResult: formatRepo, 
		 templateSelection: formatRepoSelection
	});
		
});




function formatRepo(repo){
	if (repo.loading) {
    	return repo.text;
	}
	
	return repo.text;
}

function formatRepoSelection(repo){
	
	if (repo.loading) {
    	return repo.text;
	}
	
	return repo.text;
};
</script>



</body>
</html>

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部