$.each $.map arr.forEach
var arr = ["a", "b", "c", "d", "e"];
$.each(arr, function(i,item) {
alert(item);
})
$.map(arr, function (item,i) {
alert(item);
})
var x = $(arr).filter(function (i,item) {
return i > 2 && item == "d";
})
$.each(x, function (i, item) {
alert(i + "/" + item);
}
);
arr.forEach(function (item,index) {
alert(index + "/" + item);
});
------------------------------------------------------------------------------------
$.ajax get json from ashx
<script>
$(function () {
//$('#select1').append($('<option>', {
// value: 1,
// text: 'My option1'
//})).append($('<option value="2"> My option2 </option>'));
urlToHandler = '/JQTest/Handler1.ashx';
jsonData = { company: "microsoft" };
//alert(jsonData);
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function (returnData) {
cb = "<option value=''> 請選擇 </option>";
$.each(returnData, function (i, item) {
cb += '<option value="' + item.score + '">' + item.name + '</option>';
});
$("#select1").append(cb);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
});
$(function () {
$('#select1').change(function () {
alert($(this).val());
});
});
</script>
<script>
$(function () {
$("#btn1").click(function () {
var selectedValues = $('#multipleSelect').val();
alert(selectedValues); //2,3
})
})
//sort item
$(function () {
$("#btn2").click(function () {
var $ms = $("#multipleSelect option");
$ms.sort(function (a, b) {
if (a.text < b.text) return -1;
if (a.text == b.text) return 0;
return 1;
});
$($ms).remove();
$("#multipleSelect").append($($ms));
})
})
</script>
<form id="form1" runat="server">
<select id="select1" ></select>
<input type="button" id="btn1" value="GetValue" />
<input type="button" id="btn2" value="SortText" />
<select id="multipleSelect" multiple="multiple">
<option value="1">Text 1</option>
<option value="9">Text 9</option>
<option value="7">Text 7</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
</form>
using Newtonsoft.Json;
using System.Web.Script.Serialization;
namespace WebapiTest.JQTest
{
/// <summary>
/// Handler1 的摘要描述
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string company = (string)context.Request["company"];
//string json = "";
//json += " [ ";
//json += " {\"id\":1,\"description\":\"" + company + "\"} , ";
//json += " {\"id\":2,\"description\":\"item2\"} , ";
//json += " {\"id\":3,\"description\":\"item3\"} ";
//json += " ] ";
//context.Response.ContentType = "application/json";
//context.Response.Write(json);
List<Student> student = new List<Student>();
student.Add(new Student() { name="john" , score=30});
student.Add(new Student() { name = "max", score = 78 });
student.Add(new Student() { name = "jack", score = 98 });
student.Add(new Student() { name = "rose", score = 67 });
//string json = JsonConvert.SerializeObject(student);
JavaScriptSerializer jss = new JavaScriptSerializer();
string json = jss.Serialize(student);
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
public class Student
{
public string name { set; get; }
public int score { set; get; }
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
------------------------------------------------------------------------------------
table add and remove row
<script type="text/javascript">
$(document).ready(function () {
$('#add1').click(function () {
$('#tb1 tbody').append('<tr><td onClick=javascript:doprocess(this.innerText);> 123 </td> <td onClick="javascript:alert(this.innerText);"> test </td> </tr>')
});
$('#add2').click(function () {
$('#tb1 tbody tr:last').remove();
});
//$('.c1').click(function () {
// alert($(this).text());
//});
//$('#tb1 tbody tr td').click(function () {
// alert($(this).text());
//});
});
</script>
<form id="form1" runat="server">
<a id="add1" href="javascript:void(0)">Add</a> <a id="add2" href="javascript:void(0)">Del</a> <p />
<table id="tb1" border="1" cellspacing="0" cellpadding="0" >
<tbody>
<tr>
<td> 品項 </td> <td> 數量 </td>
</tr>
</tbody>
</table>
</form>
------------------------------------------------------------------------------------
jquery ui
<script>
$(document).ready(
function () { $("#TextBox1").on('change', function () { alert($(this).val()); }) }
);
$(document).ready(
function () { $("#Button2").on('click', function () { $("#p1").fadeOut('slow', function () { alert('has closed'); }); }) }
);
$(document).ready(
function () {
$("#Button3").on('click', function () {
$("#p1").fadeIn(3000);
$("#Button3").css('display', 'none');
$("#dialog").dialog();
})
}
);
<%--function test() {
alert('<%= TextBox1.ClientID %>');
}--%>
$(document).ready(function () {
//setTimeout(
//function () {
// alert(new Date().getFullYear().toString());
//}, 5000);
});
</script>
<script>
$(document).ready(
function () {
//$("#accordion").accordion();
});
$(function () {
$("#accordion").accordion();
});
$(function () {
$("#progressbar").progressbar({
value: 37,
create: function (event, ui) { $(this).find('.ui-widget-header').css({ 'background-color': 'red' }) }
});
});
$(function () {
$("#tabs").tabs();
});
$(function () {
var x = $("#spinner").spinner();
x.spinner("value", 5);
//alert(x.spinner("value"));
});
</script>
<script>
$(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$("#tags").autocomplete({
source: availableTags
});
});
</script>
<form id="form1" runat="server">
<p/>
<input type="button" id="Button2" runat="server" value="hide" />
<input type="button" id="Button3" runat="server" value="show" />
<p id="p1">
TEST TEST TEST
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</p>
<div id="accordion">
<h3> <font style="color:red"> Section 1 </font></h3>
<div>
Section 1 Section 1 Section 1
</div>
<h3> <font style="color:red"> Section 2 </font></h3>
<div>
Section 2 Section 2 Section 2
</div>
<h3> <font style="color:red"> Section 3 </font></h3>
<div>
Section 3 Section 3 Section 3
</div>
</div>
<p />
<div class="ui-widget">
<label for="tags">AutoComplete: </label>
<input id="tags"/>
</div>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog .</p>
</div>
<div id="progressbar" style="width:600px"></div>
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<br/><br/>
<p>Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo,
Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo,
</p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis </p>
</div>
<div id="tabs-3">
<p>Duis cursus. Maecenas ligula eros, </p>
</div>
</div>
<p>
<label for="spinner">Select a value:</label>
<input id="spinner" name="value"/>
</p>
</form>
------------------------------------------------------------------------------------
jsonp
<script>
$(function () {
// Step 1:送出JSONP請求,
$('#send').click(function () {
// 最後必須是 &callback=funcion 或 &jsoncallback=function 結尾
var URL = "http://localhost:55944/JSONP/WebForm2.aspx?id=1&name=Bruce&jsoncallback=dosomething";
$.ajax({
type: 'GET',
dataType: 'jsonp', // 記得是jsonp
url: URL,
error: function (xhr, error) {
//alert('Ajax request error.');
}
})
})
});
// Step 3:收到伺服器回應後(response.write(jsonp)),執行的callback的function
function dosomething(jsonData) {
// jsonData會取得Server傳回{...json data ...}
//單筆資料
//alert(jsonData.name);
//alert(jsonData.age);
//多筆資料
$.each(jsonData, function (key, item) {
alert(key + "/" + item.name + "/" + item.age);
});
}
</script>
<form id="form1" runat="server">
<input type="button" id="send" value="send" />
</form>
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//' Step 2:進行相關處理
//'接收到的id & name處理...
//' 以下是重點,組合出function及json資料,然後回傳
string id = Request["id"].ToString();
string name = Request["name"].ToString();
string jsonp = "";
//' dosomething是 function name
// ' {...} 是json data
jsonp = "dosomething(";
//jsonp += "{\"name\":\"Joe\", \"age\":\"30\" }"; //單筆
jsonp += "[{\"name\":\"Joe\", \"age\":\"30\" },{\"name\":\"May\", \"age\":\"38\" }]"; //多筆
jsonp += ");" ;
Response.Write(jsonp);
}
}
------------------------------------------------------------------------------------
ASP.NET WEBAPI
<script>
var uri = 'api/products';
//var uri ='http://localhost:55944/api/products';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data2) {
// On success, 'data' contains a list of products.
$.each(data2, function (key, item) { //KEY 0,1,2
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
}) ;
});
function formatItem(item) {
return item.Name + ': $' + item.Price;
}
//Yo-yo: $3.75
function find() {
var id = $('#prodId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
</script>
<div>
<h2>All Products</h2>
<ul id="products" />
</div>
<div>
<h2>Search by ID</h2>
<input type="text" id="prodId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div>
//http://localhost:55944/api/products
//http://localhost:55944/api/products/2
namespace WebapiTest.Controllers
{
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts() //GET
{
return products;
}
public IHttpActionResult GetProduct(int id) //POST
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
namespace WebapiTest.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
------------------------------------------------------------------------------------
使用程式抓取WEB API 回傳值
//GET OK
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://localhost:55944/api/products" );
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "application/json";
using (var response = (HttpWebResponse)request.GetResponse( ))
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (var stream = response.GetResponseStream( ))
using (var reader = new StreamReader( stream ))
{
var temp = reader.ReadToEnd( );
//TODO:反序列化
var serializer = new JavaScriptSerializer( );
var list = serializer.Deserialize<List<Product>>( temp );
this.dataGridView1.DataSource = list;
this.txtResponse.Text = temp;
}
}
else
{
this.dataGridView1.DataSource = null;
}
}
------------------------------------------------------------------------------------
$.ajax json
$(document).ready(function () {
$('#btn3').click(function () {
$.ajax({
url: "TEST3.aspx",
cache: false,
dataType: 'json',
success: function (data) {
//for (var k in data) {
// alert(k + "/" + data[k].name + "/" + data[k].Age );
//}
$.each(data, function (key, item) {
alert(key + "/" + item.name + "/" + item.Age);
});
//單筆: data.name data.Age
//data = $.parseJSON(data); // error
}
});
})
});
string json = "[ {\"name\":\"Joe\", \"Age\":\"30\"} , {\"name\":\"Max\", \"Age\":\"20\"} ]";
Response.Write(json);
------------------------------------------------------------------------------------
error handeler
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
------------------------------------------------------------------------------------
$.blockUI
<script>
$(document).ready(function () {
$('#button2').click(function () {
$.blockUI({ overlayCSS: { backgroundColor: '#3366cc' } });
setTimeout($.unblockUI, 2000);
//location.href = 'http://www.google.com.tw';
});
});
</script>
<script>
//$j = jQuery.noConflict();
$(document).ready(function () {
$('#button3').click(function () {
$.blockUI({
message: '<div style="padding: 5px"><img src="../images/waiting.gif" /> Please Waiting </div>'
});
setTimeout(function () {
$(document).one('click', function () {
$.unblockUI();
});
}, 100);
});
});
</script>
------------------------------------------------------------------------------------
<script>
$(document).ready(
function () {
$("#Button2").click(
function () {
var str = "";
$("select#sel1 option:selected").each(function () {
str += $(this).text() + "/";
});
$("#div1").text(str);
}
)
}
function () {
$("#Button2").click(
function () {
$("#div1").text(
$("select#sel1 option:selected").map(function () {
return $(this).text();
}).get().join("/")
);
} )
});
function () {
$("input[type=radio][name=radio1]").click(
function () {
alert($("input:radio[name=radio1]:checked").val());
} )
});
</script>
<script>
$(document).ready(
function () {
$("#Button1").click(
function(e)
{
//e.preventDefault(); //prevent postback
//$("[id=Button1]").click(); //do postback
//return true;
//var cbxVehicle = new Array();
var str = "";
$('input:checkbox:checked[name="vehicle"]').each(function (i) {
str += $(this).val() + "/";
});
$("#div2").text(str);
}
)
}
);
</script>
------------------------------------------------------------------------------------
$(function(){
//JSON 未定義
//https://dotblogs.com.tw/joysdw12/archive/2011/08/01/32414.aspx
var obj = new Object();
obj.name = "mary";
obj.sex = "F";
obj.addr = "taipei";
var obj2Str = JSON.stringify(obj); //object to string
//alert(obj2Str); //{"name":"mary","sex":"F","addr":"taipei"}
var json = '{ "data" : [{"name":"mary","sex":"F","addr":"taipei"},{"name":"john","sex":"M","addr":"toyok"}] }';
var jobj = JSON.parse(json); //string to object
var len = jobj.data.length;
//for(var i = 0;i<len;i++)
//{
// //alert(jobj.data[i].name);
//}
$(jobj).each(function (i , items) {
$(items.data).each(function (j,item) {
alert(item.name);
});
});
var json2 = '[ {"name":"mary","sex":"F","addr":"taipei"} , {"name":"john","sex":"M","addr":"toyok"} ]';
var jobj2 = JSON.parse(json2);
$(jobj2).each(function (i, item) {
//alert(item.name);
});
});
------------------------------------------------------------------------------------
$(function () {
$("#btn1").on('click', function (event) {
$(this).prop('disabled', true);
alert("do something..");
alert("finished..");
$(this).prop('disabled', false);
});
});
------------------------------------------------------------------------------------
//js Array
$(function () {
var ar = new Array("a","b");
ar.push("1"); //add last
ar.unshift("2"); //add first
ar.push("3");
ar.sort();
//ar.reverse();
//ar.shift(); //remove first
//ar.pop(); //remove last
//ar.splice(0,1); //remove index ,length
//filter array
//ar = $.grep(ar, function (item, i) {
// return i > 2;
//});
//find item and remove
//var idx = $.inArray("2", ar);
//ar.splice(idx,1);
$(ar).each(function (i,item) {
alert(item);
});
});
//js []
$(function () {
var ar1 = [];
ar1.push("a");
ar1.push("b");
var ar2 = ["y", "z"];
var ar = ar1.concat(ar2);
ar = $(ar).filter(function (i ,item) {
return item > "w" ;
});
$(ar).each(function (i, item) {
//alert(item);
});
});
------------------------------------------------------------------------------------
table add row
<script>
function doprocess(val1) {
//alert(val1);
window.open("http://www.google.com.tw?k="+val1 ,"new");
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#add1').click(function () {
$('#tb1 tbody').append('<tr><td onClick=doprocess(this.innerText);> 123 </td> <td onClick="alert(this.innerText);"> test </td> </tr>')
});
$('#add2').click(function () {
$('#tb1 tbody tr:last').remove();
});
});
</script>
<a id="add1" href="javascript:void(0)">Add</a> <a id="add2" href="javascript:void(0)">Del</a> <p />
<table id="tb1" border="1" cellspacing="0" cellpadding="0" >
<tbody>
<tr>
<td> 品項 </td> <td> 數量 </td>
</tr>
</tbody>
</table>
------------------------------------------------------------------------------------
<script>
$(function () {
$("#btn1").on('click', function (event) {
//alert(event.target.type); //button
//alert(event.target.value); //calc
$("#img1").show();
$("#div1").text("please wait");
alert("in process");
$(this).prop('disabled', true);
urlToHandler = '/JQTest/Handler2.ashx';
jsonData = { company: "microsoft" };
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function (returnData) {
var rtn = "";
//$.each(returnData, function (i, item) {
// rtn += item.result + " " +item.msg ;
//});
rtn = returnData.result + " " + returnData.msg;
$("#div1").text(rtn);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
$("#img1").hide();
alert("end");
$(this).prop('disabled', false);
});
});
</script>
<input id="btn1" type="button" value="calc" />
<p />
<span id="div1"></span>
<img id="img1" style="display:none" src="../images/waiting.gif?Math.random()" />
-----------------------
using System.Web.Script.Serialization;
namespace WebapiTest.JQTest
{
/// <summary>
/// Handler2 的摘要描述
/// </summary>
public class Handler2 : IHttpHandler
{
public void ProcessRequest( HttpContext context )
{
string company = (string)context.Request[ "company" ];
var c = 0;
for (var i = 0 ; i < 100000000 ; i++)
{
c += i;
}
List<Process> process = new List<Process>( );
process.Add( new Process( )
{
result = c.ToString() ,
msg = company +" Success"
} );
Process singleProcess = new Process( )
{
result = c.ToString( ),
msg = company + " Error"
};
JavaScriptSerializer jss = new JavaScriptSerializer( );
string json = jss.Serialize( singleProcess );
context.Response.ContentType = "application/json";
context.Response.Write( json );
}
public class Process
{
public string result
{
set;
get;
}
public string msg
{
set;
get;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
------------------------------------------------------------------------------------
ajaxstart blockUi
<script>
$(function () {
$("#btn1").on('click', function (event) {
urlToHandler = '/JQTest/Handler2.ashx';
jsonData = { company: "microsoft" };
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function (returnData) {
var rtn = "";
if (returnData.result == undefined) {
$.each(returnData, function (i, item) {
rtn += item.result + " " + item.msg;
});
}
else {
rtn = returnData.result + " " + returnData.msg;
}
$("#div1").text(rtn);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
});
});
$(document).ajaxStart(function () {
$.blockUI({ message: '<img src="../images/waiting.gif" /> Please Wait..' });
}).ajaxStop($.unblockUI);
</script>
------------------------------------------------------------------------------------
var arr = ["a", "b", "c", "d", "e"];
$.each(arr, function(i,item) {
alert(item);
})
$.map(arr, function (item,i) {
alert(item);
})
var x = $(arr).filter(function (i,item) {
return i > 2 && item == "d";
})
$.each(x, function (i, item) {
alert(i + "/" + item);
}
);
arr.forEach(function (item,index) {
alert(index + "/" + item);
});
------------------------------------------------------------------------------------
$.ajax get json from ashx
<script>
$(function () {
//$('#select1').append($('<option>', {
// value: 1,
// text: 'My option1'
//})).append($('<option value="2"> My option2 </option>'));
urlToHandler = '/JQTest/Handler1.ashx';
jsonData = { company: "microsoft" };
//alert(jsonData);
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function (returnData) {
cb = "<option value=''> 請選擇 </option>";
$.each(returnData, function (i, item) {
cb += '<option value="' + item.score + '">' + item.name + '</option>';
});
$("#select1").append(cb);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
});
$(function () {
$('#select1').change(function () {
alert($(this).val());
});
});
</script>
<script>
$(function () {
$("#btn1").click(function () {
var selectedValues = $('#multipleSelect').val();
alert(selectedValues); //2,3
})
})
//sort item
$(function () {
$("#btn2").click(function () {
var $ms = $("#multipleSelect option");
$ms.sort(function (a, b) {
if (a.text < b.text) return -1;
if (a.text == b.text) return 0;
return 1;
});
$($ms).remove();
$("#multipleSelect").append($($ms));
})
})
</script>
<form id="form1" runat="server">
<select id="select1" ></select>
<input type="button" id="btn1" value="GetValue" />
<input type="button" id="btn2" value="SortText" />
<select id="multipleSelect" multiple="multiple">
<option value="1">Text 1</option>
<option value="9">Text 9</option>
<option value="7">Text 7</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
</form>
using Newtonsoft.Json;
using System.Web.Script.Serialization;
namespace WebapiTest.JQTest
{
/// <summary>
/// Handler1 的摘要描述
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string company = (string)context.Request["company"];
//string json = "";
//json += " [ ";
//json += " {\"id\":1,\"description\":\"" + company + "\"} , ";
//json += " {\"id\":2,\"description\":\"item2\"} , ";
//json += " {\"id\":3,\"description\":\"item3\"} ";
//json += " ] ";
//context.Response.ContentType = "application/json";
//context.Response.Write(json);
List<Student> student = new List<Student>();
student.Add(new Student() { name="john" , score=30});
student.Add(new Student() { name = "max", score = 78 });
student.Add(new Student() { name = "jack", score = 98 });
student.Add(new Student() { name = "rose", score = 67 });
//string json = JsonConvert.SerializeObject(student);
JavaScriptSerializer jss = new JavaScriptSerializer();
string json = jss.Serialize(student);
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
public class Student
{
public string name { set; get; }
public int score { set; get; }
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
------------------------------------------------------------------------------------
table add and remove row
<script type="text/javascript">
$(document).ready(function () {
$('#add1').click(function () {
$('#tb1 tbody').append('<tr><td onClick=javascript:doprocess(this.innerText);> 123 </td> <td onClick="javascript:alert(this.innerText);"> test </td> </tr>')
});
$('#add2').click(function () {
$('#tb1 tbody tr:last').remove();
});
//$('.c1').click(function () {
// alert($(this).text());
//});
//$('#tb1 tbody tr td').click(function () {
// alert($(this).text());
//});
});
</script>
<form id="form1" runat="server">
<a id="add1" href="javascript:void(0)">Add</a> <a id="add2" href="javascript:void(0)">Del</a> <p />
<table id="tb1" border="1" cellspacing="0" cellpadding="0" >
<tbody>
<tr>
<td> 品項 </td> <td> 數量 </td>
</tr>
</tbody>
</table>
</form>
------------------------------------------------------------------------------------
jquery ui
<script>
$(document).ready(
function () { $("#TextBox1").on('change', function () { alert($(this).val()); }) }
);
$(document).ready(
function () { $("#Button2").on('click', function () { $("#p1").fadeOut('slow', function () { alert('has closed'); }); }) }
);
$(document).ready(
function () {
$("#Button3").on('click', function () {
$("#p1").fadeIn(3000);
$("#Button3").css('display', 'none');
$("#dialog").dialog();
})
}
);
<%--function test() {
alert('<%= TextBox1.ClientID %>');
}--%>
$(document).ready(function () {
//setTimeout(
//function () {
// alert(new Date().getFullYear().toString());
//}, 5000);
});
</script>
<script>
$(document).ready(
function () {
//$("#accordion").accordion();
});
$(function () {
$("#accordion").accordion();
});
$(function () {
$("#progressbar").progressbar({
value: 37,
create: function (event, ui) { $(this).find('.ui-widget-header').css({ 'background-color': 'red' }) }
});
});
$(function () {
$("#tabs").tabs();
});
$(function () {
var x = $("#spinner").spinner();
x.spinner("value", 5);
//alert(x.spinner("value"));
});
</script>
<script>
$(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$("#tags").autocomplete({
source: availableTags
});
});
</script>
<form id="form1" runat="server">
<p/>
<input type="button" id="Button2" runat="server" value="hide" />
<input type="button" id="Button3" runat="server" value="show" />
<p id="p1">
TEST TEST TEST
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</p>
<div id="accordion">
<h3> <font style="color:red"> Section 1 </font></h3>
<div>
Section 1 Section 1 Section 1
</div>
<h3> <font style="color:red"> Section 2 </font></h3>
<div>
Section 2 Section 2 Section 2
</div>
<h3> <font style="color:red"> Section 3 </font></h3>
<div>
Section 3 Section 3 Section 3
</div>
</div>
<p />
<div class="ui-widget">
<label for="tags">AutoComplete: </label>
<input id="tags"/>
</div>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog .</p>
</div>
<div id="progressbar" style="width:600px"></div>
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<br/><br/>
<p>Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo,
Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo, Proin elit arcu, rutrum commodo,
</p>
</div>
<div id="tabs-2">
<p>Morbi tincidunt, dui sit amet facilisis </p>
</div>
<div id="tabs-3">
<p>Duis cursus. Maecenas ligula eros, </p>
</div>
</div>
<p>
<label for="spinner">Select a value:</label>
<input id="spinner" name="value"/>
</p>
</form>
------------------------------------------------------------------------------------
jsonp
<script>
$(function () {
// Step 1:送出JSONP請求,
$('#send').click(function () {
// 最後必須是 &callback=funcion 或 &jsoncallback=function 結尾
var URL = "http://localhost:55944/JSONP/WebForm2.aspx?id=1&name=Bruce&jsoncallback=dosomething";
$.ajax({
type: 'GET',
dataType: 'jsonp', // 記得是jsonp
url: URL,
error: function (xhr, error) {
//alert('Ajax request error.');
}
})
})
});
// Step 3:收到伺服器回應後(response.write(jsonp)),執行的callback的function
function dosomething(jsonData) {
// jsonData會取得Server傳回{...json data ...}
//單筆資料
//alert(jsonData.name);
//alert(jsonData.age);
//多筆資料
$.each(jsonData, function (key, item) {
alert(key + "/" + item.name + "/" + item.age);
});
}
</script>
<form id="form1" runat="server">
<input type="button" id="send" value="send" />
</form>
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//' Step 2:進行相關處理
//'接收到的id & name處理...
//' 以下是重點,組合出function及json資料,然後回傳
string id = Request["id"].ToString();
string name = Request["name"].ToString();
string jsonp = "";
//' dosomething是 function name
// ' {...} 是json data
jsonp = "dosomething(";
//jsonp += "{\"name\":\"Joe\", \"age\":\"30\" }"; //單筆
jsonp += "[{\"name\":\"Joe\", \"age\":\"30\" },{\"name\":\"May\", \"age\":\"38\" }]"; //多筆
jsonp += ");" ;
Response.Write(jsonp);
}
}
------------------------------------------------------------------------------------
ASP.NET WEBAPI
<script>
var uri = 'api/products';
//var uri ='http://localhost:55944/api/products';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data2) {
// On success, 'data' contains a list of products.
$.each(data2, function (key, item) { //KEY 0,1,2
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products'));
});
}) ;
});
function formatItem(item) {
return item.Name + ': $' + item.Price;
}
//Yo-yo: $3.75
function find() {
var id = $('#prodId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
</script>
<div>
<h2>All Products</h2>
<ul id="products" />
</div>
<div>
<h2>Search by ID</h2>
<input type="text" id="prodId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="product" />
</div>
//http://localhost:55944/api/products
//http://localhost:55944/api/products/2
namespace WebapiTest.Controllers
{
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts() //GET
{
return products;
}
public IHttpActionResult GetProduct(int id) //POST
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
namespace WebapiTest.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
------------------------------------------------------------------------------------
使用程式抓取WEB API 回傳值
//GET OK
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://localhost:55944/api/products" );
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "application/json";
using (var response = (HttpWebResponse)request.GetResponse( ))
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (var stream = response.GetResponseStream( ))
using (var reader = new StreamReader( stream ))
{
var temp = reader.ReadToEnd( );
//TODO:反序列化
var serializer = new JavaScriptSerializer( );
var list = serializer.Deserialize<List<Product>>( temp );
this.dataGridView1.DataSource = list;
this.txtResponse.Text = temp;
}
}
else
{
this.dataGridView1.DataSource = null;
}
}
------------------------------------------------------------------------------------
$.ajax json
$(document).ready(function () {
$('#btn3').click(function () {
$.ajax({
url: "TEST3.aspx",
cache: false,
dataType: 'json',
success: function (data) {
//for (var k in data) {
// alert(k + "/" + data[k].name + "/" + data[k].Age );
//}
$.each(data, function (key, item) {
alert(key + "/" + item.name + "/" + item.Age);
});
//單筆: data.name data.Age
//data = $.parseJSON(data); // error
}
});
})
});
string json = "[ {\"name\":\"Joe\", \"Age\":\"30\"} , {\"name\":\"Max\", \"Age\":\"20\"} ]";
Response.Write(json);
------------------------------------------------------------------------------------
error handeler
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
------------------------------------------------------------------------------------
$.blockUI
<script>
$(document).ready(function () {
$('#button2').click(function () {
$.blockUI({ overlayCSS: { backgroundColor: '#3366cc' } });
setTimeout($.unblockUI, 2000);
//location.href = 'http://www.google.com.tw';
});
});
</script>
<script>
//$j = jQuery.noConflict();
$(document).ready(function () {
$('#button3').click(function () {
$.blockUI({
message: '<div style="padding: 5px"><img src="../images/waiting.gif" /> Please Waiting </div>'
});
setTimeout(function () {
$(document).one('click', function () {
$.unblockUI();
});
}, 100);
});
});
</script>
------------------------------------------------------------------------------------
<script>
$(document).ready(
function () {
$("#Button2").click(
function () {
var str = "";
$("select#sel1 option:selected").each(function () {
str += $(this).text() + "/";
});
$("#div1").text(str);
}
)
}
function () {
$("#Button2").click(
function () {
$("#div1").text(
$("select#sel1 option:selected").map(function () {
return $(this).text();
}).get().join("/")
);
} )
});
function () {
$("input[type=radio][name=radio1]").click(
function () {
alert($("input:radio[name=radio1]:checked").val());
} )
});
</script>
<script>
$(document).ready(
function () {
$("#Button1").click(
function(e)
{
//e.preventDefault(); //prevent postback
//$("[id=Button1]").click(); //do postback
//return true;
//var cbxVehicle = new Array();
var str = "";
$('input:checkbox:checked[name="vehicle"]').each(function (i) {
str += $(this).val() + "/";
});
$("#div2").text(str);
}
)
}
);
</script>
------------------------------------------------------------------------------------
$(function(){
//JSON 未定義
//https://dotblogs.com.tw/joysdw12/archive/2011/08/01/32414.aspx
var obj = new Object();
obj.name = "mary";
obj.sex = "F";
obj.addr = "taipei";
var obj2Str = JSON.stringify(obj); //object to string
//alert(obj2Str); //{"name":"mary","sex":"F","addr":"taipei"}
var json = '{ "data" : [{"name":"mary","sex":"F","addr":"taipei"},{"name":"john","sex":"M","addr":"toyok"}] }';
var jobj = JSON.parse(json); //string to object
var len = jobj.data.length;
//for(var i = 0;i<len;i++)
//{
// //alert(jobj.data[i].name);
//}
$(jobj).each(function (i , items) {
$(items.data).each(function (j,item) {
alert(item.name);
});
});
var json2 = '[ {"name":"mary","sex":"F","addr":"taipei"} , {"name":"john","sex":"M","addr":"toyok"} ]';
var jobj2 = JSON.parse(json2);
$(jobj2).each(function (i, item) {
//alert(item.name);
});
});
------------------------------------------------------------------------------------
$(function () {
$("#btn1").on('click', function (event) {
$(this).prop('disabled', true);
alert("do something..");
alert("finished..");
$(this).prop('disabled', false);
});
});
------------------------------------------------------------------------------------
//js Array
$(function () {
var ar = new Array("a","b");
ar.push("1"); //add last
ar.unshift("2"); //add first
ar.push("3");
ar.sort();
//ar.reverse();
//ar.shift(); //remove first
//ar.pop(); //remove last
//ar.splice(0,1); //remove index ,length
//filter array
//ar = $.grep(ar, function (item, i) {
// return i > 2;
//});
//find item and remove
//var idx = $.inArray("2", ar);
//ar.splice(idx,1);
$(ar).each(function (i,item) {
alert(item);
});
});
//js []
$(function () {
var ar1 = [];
ar1.push("a");
ar1.push("b");
var ar2 = ["y", "z"];
var ar = ar1.concat(ar2);
ar = $(ar).filter(function (i ,item) {
return item > "w" ;
});
$(ar).each(function (i, item) {
//alert(item);
});
});
------------------------------------------------------------------------------------
table add row
<script>
function doprocess(val1) {
//alert(val1);
window.open("http://www.google.com.tw?k="+val1 ,"new");
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#add1').click(function () {
$('#tb1 tbody').append('<tr><td onClick=doprocess(this.innerText);> 123 </td> <td onClick="alert(this.innerText);"> test </td> </tr>')
});
$('#add2').click(function () {
$('#tb1 tbody tr:last').remove();
});
});
</script>
<a id="add1" href="javascript:void(0)">Add</a> <a id="add2" href="javascript:void(0)">Del</a> <p />
<table id="tb1" border="1" cellspacing="0" cellpadding="0" >
<tbody>
<tr>
<td> 品項 </td> <td> 數量 </td>
</tr>
</tbody>
</table>
------------------------------------------------------------------------------------
<script>
$(function () {
$("#btn1").on('click', function (event) {
//alert(event.target.type); //button
//alert(event.target.value); //calc
$("#img1").show();
$("#div1").text("please wait");
alert("in process");
$(this).prop('disabled', true);
urlToHandler = '/JQTest/Handler2.ashx';
jsonData = { company: "microsoft" };
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function (returnData) {
var rtn = "";
//$.each(returnData, function (i, item) {
// rtn += item.result + " " +item.msg ;
//});
rtn = returnData.result + " " + returnData.msg;
$("#div1").text(rtn);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
$("#img1").hide();
alert("end");
$(this).prop('disabled', false);
});
});
</script>
<input id="btn1" type="button" value="calc" />
<p />
<span id="div1"></span>
<img id="img1" style="display:none" src="../images/waiting.gif?Math.random()" />
-----------------------
using System.Web.Script.Serialization;
namespace WebapiTest.JQTest
{
/// <summary>
/// Handler2 的摘要描述
/// </summary>
public class Handler2 : IHttpHandler
{
public void ProcessRequest( HttpContext context )
{
string company = (string)context.Request[ "company" ];
var c = 0;
for (var i = 0 ; i < 100000000 ; i++)
{
c += i;
}
List<Process> process = new List<Process>( );
process.Add( new Process( )
{
result = c.ToString() ,
msg = company +" Success"
} );
Process singleProcess = new Process( )
{
result = c.ToString( ),
msg = company + " Error"
};
JavaScriptSerializer jss = new JavaScriptSerializer( );
string json = jss.Serialize( singleProcess );
context.Response.ContentType = "application/json";
context.Response.Write( json );
}
public class Process
{
public string result
{
set;
get;
}
public string msg
{
set;
get;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
------------------------------------------------------------------------------------
ajaxstart blockUi
<script>
$(function () {
$("#btn1").on('click', function (event) {
urlToHandler = '/JQTest/Handler2.ashx';
jsonData = { company: "microsoft" };
$.ajax({
url: urlToHandler,
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: 'application/json',
success: function (returnData) {
var rtn = "";
if (returnData.result == undefined) {
$.each(returnData, function (i, item) {
rtn += item.result + " " + item.msg;
});
}
else {
rtn = returnData.result + " " + returnData.msg;
}
$("#div1").text(rtn);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
});
});
$(document).ajaxStart(function () {
$.blockUI({ message: '<img src="../images/waiting.gif" /> Please Wait..' });
}).ajaxStop($.unblockUI);
</script>
------------------------------------------------------------------------------------