我正在使用 jquery 和 ajax 将数据从一个页面发送到另一个页面,并将其作为 html 内容附加到一个元素。我使用 angularJS 路由为我的所有页面创建一个单页应用程序。 现在在我的主页中使用 jquery ,当我将数据提交到模式框时,我重定向而不重新加载到使用(angularJS)显示给定数据的页面。问题是,当第一次触发事件时,我成功重定向,但没有加载给定的数据。如果我打开模态并再次触发事件,则数据将正常加载。它只是第一次不起作用。在检查更多之后,我意识到必须先访问我的结果页面一次,然后才能正确执行我的函数并加载页面上的数据。我想知道如何解决这个问题。
JQUERY(文档准备好):
$("#submitSearch").click(()=>{
var inptVal = $("#ModalInput")[0].value; //get input from modal box
if(!inptVal){
alert("Enter a product ");
}else{
$.ajax({
url:'searchResults.php', //this is the php script that returns the html
type:'POST',
data:{
searchItem:inptVal,
},
cache:false,
success:(data)=>{
console.log({data}); //the returned html is correct
window.location.href='../php/index.php#!/results'; //this is where I redirect
$('.res-center').empty(); //empty the element
$('.res-center').append(data); //insert the html to the element
},
error:(xhr)=>{
alert(xhr);
}
})
}
用于路由的angularJS:
var app = angular.module("myApp" , ["ngRoute"]);
app.config(($routeProvider)=>{
$routeProvider
.when("/" , {templateUrl:"main.php"})
.when("/login" , {templateUrl : "login.php"})
.when("/register" , {templateUrl : "register.php"})
.when("/results" , {templateUrl : "showResults.php"});
});
searchResults.php 从 mongodb 数据返回 html 元素
<?php
require '../vendor/autoload.php';
if(isset($_POST['searchItem'])){
try{
$m = new MongoDB\Client("mongodb://127.0.0.1/");
$db = $m ->ECommerce;
$collection = $db->products;
$item = $_POST['searchItem'];
$cursor = $collection->find( array('title'=> new \MongoDB\BSON\Regex($item ,'i') ) );
$count = 0;
foreach($cursor as $doc){
$count++;
}
if($count==0){
echo "<h1> No items found </h1>";
exit();
}else{
$prods = $collection->find( array('title'=> new \MongoDB\BSON\Regex($item ,'i') ) );
foreach ($prods as $dc){
echo
" <div class= 'product category__products'>
<div class='product__header'>
<img src = ".$dc["image"]." />";
echo "
</div>
<div class= 'product__footer'>
<h2> ".$dc["title"]." </h2>
<h5> Public Stores </h5>
<div class= 'product__price'>
<h4> $".$dc["price"]." </h4>
</div>
<a href='#'><button type='submit' class='product__btn'>Add To Cart</button></a>
</div>
</div>
";
}
exit();
}
}catch(Exception $e){
echo $e->getMessage();
exit();
}
}else{
echo "No input";
exit();
}
?>
如有任何澄清,请询问。