我正在开发一个jQuery Mobile App,它都是前端,根本没有后端服务器代码。
因此,为了处理<form method="get">...</form>
我有一些jQuery解析URL以获取查询字符串参数。
表单目标页面上的jQuery代码如下:
// Get Query String Values
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
var searchedProduct = urlParams['name'];
var productTitle = $('.product-title');
var productImage = $('.product-image img');
//start ajax request
$.ajax({
url: "data/results.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
$.each(json.products, function(i, item) {
if(item.name.toLowerCase() === searchedProduct.toLowerCase())
{
productTitle.html(item.name);
productImage.attr('src', item.image);
productImage.attr('alt', item.name);
}
});
}
});
我提交表单的初始页面如下:
<div data-role="content">
<form action="results.html" method="get" id="product-search-form">
<p>Let us save you some money, begin your searh below</p>
<input type="text" name="name" id="name" value="" placeholder="Type your search query" data-clear-btn="true" />
<input type="submit" data-role="button" data-icon="search" data-theme="a" class="search-btn" value="Search" />
</form>
</div><!-- /content -->
参数name=cocacola
通过表单输入(即我输入cocacola并提交表单),但是当页面加载时,我看不到单词CocaCola
和{的图像{1}}通过JSON文件,我必须刷新页面,然后显示!
我的猜测是因为下面的页面内容:
CocaCola
在jQuery / JavaScript完成它的魔力之前加载。如果没有我刷新页面以查看预期结果,我怎么能让它工作?