我正在使用Spring MVC。在控制器内部,我从模型中获取列表对象并将此列表传递给视图。我将循环索引传递给javascript函数。但是现在我想通过javascript中的索引获取每个对象的值。我该怎么做?这是我的控制器类:
@RequestMapping(method = RequestMethod.GET)
public Model handleRequest(HttpServletRequest request,
HttpServletResponse response,
@RequestParam(required = false, value = "q") String query) throws Exception {
Model model = new ExtendedModelMap();
String orderItem = request.getParameter("order_item");
List<Long> itemsIdList = new ArrayList<Long>();
List<OrderRequest> orderRequestList = getItemToppingCount(orderItem,itemsIdList);
model.addAttribute("itemsSelected", orderRequestList);
return model;
}
这是我的JSP:
<script>
function remove_confirm_order(index){
alert(index); // OK
// Get value of first object in list
var str1 = '${itemsSelected[0].name}';
// When adding this line, I can't show anything from JSP
var str2 = '${itemsSelected['+index+'].name}';
alert(str1);
}
</script>
<c:forEach var="item" items="${itemsSelected}" varStatus="loop">
<a href="#" onclick="remove_confirm_order('${loop.index}');" />
</c:forEach>
答案 0 :(得分:0)
您可以在下面的代码段中获得相同的内容:
$str = 'Bellevue,Bergouey |Bergouey,Bourdious';
$str = preg_replace('~(\w+)\s*\|(\1)~', '$2', $str);
echo $str; //=> "Bellevue,Bergouey,Bourdious"
最好是从<script>
function remove_confirm_order(index, item){
alert(index); // OK
alert(item); //OrderRequest
var orderRequest = item;
// Now extract value from item(instance of OrderRequest), example, orderRequest.getValue(index);
// Get value of first object in list
var str1 = '${itemsSelected[0].name}';
// When adding this line, I can't show anything from JSP
var str2 = '${itemsSelected['+index+'].name}';
alert(str1);
}
</script>
<c:forEach var="item" items="${itemsSelected}" varStatus="loop">
<a href="#" onclick="remove_confirm_order('${loop.index}', ${item});" />
</c:forEach>
对控制器进行AJAX
调用,获取回复并做任何你想做的事情。
JavaScript
答案 1 :(得分:0)
你可以这样做。
$urls = array(
'example.com/?foo=bar',
'example.com/?bar=foo&foo=bar',
'example.com/?foo=bar&bar=foo',
);
echo 'Original' . PHP_EOL;
foreach ($urls as $url) {
echo $url . PHP_EOL;
}
echo PHP_EOL . '@AaronHathaway' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('#&?foo=[^&]*#', null, $url) . PHP_EOL;
}
echo PHP_EOL . '@SergeS' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace( "/&{2,}/", "&", preg_replace( "/foo=[^&]+/", "", $url)) . PHP_EOL;
}
echo PHP_EOL . '@Justin' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('/([?&])foo=[^&]+(&|$)/', '$1', $url) . PHP_EOL;
}
echo PHP_EOL . '@kraftb' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('/(&|\?)foo=[^&]*&/', '$1', preg_replace('/(&|\?)foo=[^&]*$/', '', $url)) . PHP_EOL;
}
echo PHP_EOL . 'My version' . PHP_EOL;
foreach ($urls as $url) {
echo str_replace('/&', '/?', preg_replace('#[&?]foo=[^&]*#', null, $url)) . PHP_EOL;
}
&#13;
您在javascript中创建一个数组。然后在脚本标记中使用jsp标记,可以将数据填充到数组中。记得在顶部
进行jstl声明