javascript ajax variable question
Hey there, new to AJAX, JS.. Im trying to add to a Javascript/Ajax search script that I've put together. Previously, it had a single search field, called search_word, I added one called search_date.
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var search_date = $("#datepicker").val();
var dataString = 'search_word='+ search_word;
if(search_word=='')
{
}
else
{
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
In the Ajax, it appears to pass data of dataString, to my processing script. How do I add search date to the dataString so that I can use that var in my searchdata.php?
In searchdata, I can do this $search_word=$_GET['search_word']; and 开发者_运维百科use that var, but so far every time i attempt to alter the dataString, it breaks all the other functionality.
Thanks!
Either
var dataString = 'search_word='+search_word+'&search_date='+search_date;
Or you can get rid of that line completely and just do
$.ajax({
type: "GET",
url: "searchdata.php",
data: {search_word: search_word, search_date: search_date}
});
You need to modify dataString
like so:
var dataString = 'search_word='+ search_word + '&search_date=' + search_date;
I also suggest you invert your if condition, to if(search_word) { ... }
, put the AJAX in there, and skip the else
.
If this doesn't help you, try alerting out the value of dataString
after that concatenation, to see what is really happening. perhaps the value of search_date
is not what you think it is?
var str = 'search_word='+ search_word + '&search_date'+search_date;
dataString = encodeURI(str);
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString});
To avoid unexpected requests to the server, you should call encodeURI on any user-entered parameters that will be passed as part of a URI.
You can also directly add it to the url:
$.ajax({
type: "GET",
url: "searchdata.php?search_word=" + search_word;
});
In your $.ajax call you can use an object for the data parameter.
$.ajax({ type: "GET", url: "searchdata.php", data: {search_word: search_word, search_date: search_date} });
Make the data a json object with your parameters:
data {
prop1: val1
, prop2: val2
}
精彩评论