我正在尝试访问 php 中的无序列表元素,以便将它们插入数据库中,我需要能够通过位置访问它们,但我不确定如何在 PHP 中执行此操作。我使用 jQuery,以便列表可以在客户端排序。 在 Javascript 中可以使用
访问它alert($("#sortable li:first").text() + ' is first ' + $("#sortable li:eq(1)").text() + ' is second ' + $("#sortable li:eq(11)").text() + ' is last');
我正在使用的列表位于 http://jsfiddle.net/mMTtc/
我只是在寻求有关如何将这些列表项存储在 php 变量中的帮助,即假设我想要根据用户对列表的排序方式获取第 6 个元素。 我该怎么做?
谢谢
最佳答案
使用以下代码,您可以在用户更改前端中元素的顺序时将更新发送到 PHP 后端:
$("#sortable").on("sortupdate", function() {
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
var dataStr = '{"newOrder":' + JSON.stringify(dataArr) + '}';
$.ajax({
url: "<url_to_php_file>",
data: dataStr
});
// alert(dataStr);
});
实例(前端部分):here
您必须替换 <url_to_php_file>
与处理元素顺序的 PHP 文件的路径(即将它们保存在数据库中)。该文件将能够以正常的 PHP Array 访问用户定义的顺序,使用json_decode($_POST["newOrder"])
,即
...
$newOrder = json_decode($_POST["newOrder"]);
for ($i = 0; $i < count($newOrder); $i++) {
echo("The item labeled '" . $newOrder[$i] . "' is placed by the user at index " . $i . ".\n";
/* 1st item: index 0 */
/* 2st item: index 1 */
/* ... */
}
示例:
您向用户呈现一个可排序列表,其中包含项目:item1、item2、item3(按此顺序)。
用户将 item2 放在 item1 之前,此时将进行 AJAX 调用,将数组 ["item2", "item1", "item3"]
传递到服务器(注意顺序)。上面的代码片段将回显:
The item labeled 'item2' is placed by the user at index 0.
The item labeled 'item1' is placed by the user at index 1.
The item labeled 'item3' is placed by the user at index 2.
(当然,您可以更新数据库中每个项目的索引字段的值或执行一些有用的操作,而不是回显任何内容。)
关于php - 在 PHP 中访问 HTML 无序列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16471787/