![](/img/trans.png)
[英]How to call function written in main file into ajax file in php & jquery
[英]how to call php file in ajax function?
我遇到了我無法解決的問題。 部分原因是我無法用正確的術語進行解釋。 我對此很陌生,所以很抱歉這個笨拙的問題。
在下面您可以看到我的目標概述。我試圖在動態下拉列表中獲取所有類別ID,第二個下拉列表基於第一個下拉列表選擇,我在本地找到了一些可以正常工作的代碼,但是我嘗試在內部magento其不起作用為什么?
這是我的代碼
<tr>
<td class="tdpadfirst">
<label for="category" class="rightgap"><?php echo Mage::helper('marketplacepartner')->__('Product Category') ?>:</label>
<span class="required starimp"> </span>
</td>
<td class="tdpadfirst">
<select id="category" class="myinput-text required-entry widthinput" name="category" onChange="updateCategory(this.value)">
<option value="">--Select Categories--</option>
<?php
include('db.php');
$sql=mysql_query("select entity_id from catalog_category_entity where level='2';");
while($row=mysql_fetch_array($sql)) {
$id=$row['entity_id'];
$data=$row['parent_id'];?>
<!--echo '<option value="'.$entity_id.'">'.$parent_id.'</option>';-->
<option value="<?php echo $id ?>"><?php echo $id ?></option>
<?php } ?>
</select>
<select name="city" class="city">
<option selected="selected">--Select subcategory--</option>
</select></td></tr>
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".country").change(function() {
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax ({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html) {
$(".city").html(html);
}
});
});
});
ajax_city.php是:
<?php
include('db.php');
if($_POST['id']) {
$id=$_POST['id'];
$sql=mysql_query("select entity_id from catalog_category_entity where parent_id='$id'");
while($row=mysql_fetch_array($sql)) {
$id=$row['entity_id'];
$data=$row['parent_id'];
echo '<option value="'.$data.'">'.$id.'</option>';
}
}
?>
db.php是:
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "admin";
$mysql_database = "magento16";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
可以用“它在本地工作正常,但我嘗試在magento內部工作不正常嗎”來指定您的意思?
我不確定100%是否已根據您的問題進行了此操作。 嘗試僅用html替換ajax_city.php中的php代碼,您也許可以找出問題所在。
您可能需要根據設置來允許跨域訪問。 嘗試將此代碼添加到您的ajax_city.php頁面。
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
無關緊要的是,編寫ajax_city.php文件的方式使自己容易受到SQL注入的攻擊。 假設您在sql中的“ $ id”值應該是整數,則可以簡單地強制類型轉換來防止sql注入。
...entity_id from catalog_category_entity where parent_id='$id'");
更改:
$id=$_POST['id'];
至:
$ id = intval($ _ POST ['id']);
希望這可以幫助!
您確定ajax文件的路徑正確嗎,我認為magento具有基本的.htaccess。 通過檢查瀏覽器中發送的NET請求,檢查實際上是否正在調用您正在調用的ajax文件,可能是在firefox或chromes默認調試器中使用了firebug。 如果其在magento外部的正常工作和文件路徑仍然正確並且數據未顯示,請嘗試使用mage :: catalog_category模型在magento中構建一個簡單模塊。 我希望它可以幫助.. :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.