我遇到了这个问题,无法解决。部分原因是我无法用正确的术语来解释它。我是新手,很抱歉提出这个笨拙的问题。
下面您可以看到我的目标的概述。我尝试在动态下拉列表中获取所有类别 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 注入(inject)的攻击。假设您的 sql 中的“$id”值应该是一个整数,您可以简单地强制类型转换以防止 sql 注入(inject)。
...entity_id from catalog_category_entity where parent_id='$id'");
更改:
$id=$_POST['id'];
致:
$id=intval($_POST['id']);
希望这有帮助!
关于php - 如何在ajax函数中调用php文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17692091/