שולח בקשת http POST אסינכרונית לטעינת נתונים מהשרת. צורתו הכללית היא:
jQuery.post( url [, data ] [, success ] [, dataType ] )
- url: הוא הפרמטר החובה היחיד. מחרוזת זו מכילה את הכתובת שאליה לשלוח את הבקשה. מהנתונים שהוחזרו יתעלם אם לא צויין פרמטר אחר
- נתונים: אובייקט או מחרוזת רגילים שנשלחים לשרת עם הבקשה.
- הצלחה: פונקציית התקשרות חוזרת שמתבצעת אם הבקשה מצליחה. זה לוקח כארגומנט את הנתונים שהוחזרו. הוא עבר גם את מצב הטקסט של התגובה.
- dataType: סוג הנתונים הצפוי מהשרת. ברירת המחדל היא Intelligent Guess (xml, json, script, text, html). אם פרמטר זה מסופק, יש לספק גם את התקשרות החזרה.
דוגמאות
$.post('//example.com/form.php', {category:'client', type:'premium'});
בקשות form.php
מהשרת, שליחת נתונים נוספים והתעלמות מהתוצאה שהוחזרה
$.post('//example.com/form.php', {category:'client', type:'premium'}, function(response){ alert("success"); $("#mypar").html(response.amount); });
בקשות form.php
מהשרת, שליחת נתונים נוספים וטיפול בתגובה שהוחזרה (פורמט json). ניתן לכתוב דוגמה זו בפורמט זה:
$.post('//example.com/form.php', {category:'client', type:'premium'}).done(function(response){ alert("success"); $("#mypar").html(response.amount); });
הדוגמה הבאה מפרסמת טופס באמצעות Ajax ומציבה תוצאות בחלוקה
jQuery.post demo // Attach a submit handler to the form $( "#searchForm" ).submit(function( event ) { // Stop form from submitting normally event.preventDefault(); // Get some values from elements on the page: var $form = $( this ), term = $form.find( "input[name='s']" ).val(), url = $form.attr( "action" ); // Send the data using post var posting = $.post( url, { s: term } ); // Put the results in a div posting.done(function( data ) { var content = $( data ).find( "#content" ); $( "#result" ).empty().append( content ); }); });
הדוגמה הבאה משתמשת ב- API של github כדי להביא את רשימת המאגרים של משתמש המשתמשת ב- jQuery.ajax () ולהכניס תוצאות לחלוקה
jQuery Get demo // Attach a submit handler to the form $( "#userForm" ).submit(function( event ) { // Stop form from submitting normally event.preventDefault(); // Get some values from elements on the page: var $form = $( this ), username = $form.find( "input[name='username']" ).val(), url = "//api.github.com/users/"+username+"/repos"; // Send the data using post var posting = $.post( url, { s: term } ); //Ajax Function to send a get request $.ajax({ type: "GET", url: url, dataType:"jsonp" success: function(response){ //if request if made successfully then the response represent the data $( "#result" ).empty().append( response ); } }); });
jQuery.ajax ()
$.post( url [, data ] [, success ] [, dataType ] )
היא פונקציית Ajax קצרה, המקבילה ל:
$.ajax({ type: "POST", url: url, data: data, success: success, dataType: dataType });
$.ajax()
מספק אפשרויות רבות יותר שניתן למצוא כאן
עוד מידע:
למידע נוסף אנא בקרו באתר הרשמי