简体   繁体   English

从回显的 php 传递数据

[英]Passing data from an echoed php

I am currently trying to pass data from my server to my main page.我目前正在尝试将数据从我的服务器传递到我的主页。 I currently have my php echoing for each returned result:我目前有我的 php 回显每个返回的结果:

while($row = mysql_fetch_array($result))
{
    echo "<img class='s' id=" . $row['id'] . " src=QR/" . $row['src'] ".png>";

}

when i tried adding a field, num, after id:当我尝试在 id 之后添加一个字段 num 时:

<img class='s' id=(rowid) num=".$row['num']." .......

I get undefined when i use我使用时不确定

alert(this.num)

but

alert(this.id)

works.作品。 How can I pass the num value too?我怎样才能传递 num 值呢?

EDIT:编辑:

Hey Everyone, thanks for you help, I have included a jsfiddle on how i solved this problem.嘿大家,谢谢你的帮助,我已经包含了一个关于我如何解决这个问题的jsfiddle。 http://jsfiddle.net/3yzcx/4/ http://jsfiddle.net/3yzcx/4/

I had to use jQuery and used.attr() to define my own attribute called num and called that out.我不得不使用 jQuery 和 used.attr() 来定义我自己的名为 num 的属性并将其调用。

Very simple.很简单。 id is a valid property for the img tag. idimg标签的有效属性。 num is not. num不是。 You can't assign arbitrary properties to a tag and expect it to work.您不能将任意属性分配给标签并期望它起作用。

If you want to pass your PHP data to javascript, using a hidden form element or even more simply something like this:如果您想将 PHP 数据传递给 javascript,请使用隐藏的表单元素或更简单的方式:

<?php
echo '<script type="text/javascript">';
echo 'var num = ' . $num . ';';
echo '</script>';
?>

Of course I know you're in a loop, this is just an example.当然我知道你在循环中,这只是一个例子。 You could easily make it an array or something.你可以很容易地把它变成一个数组或其他东西。

Adding properties doesn't work.添加属性不起作用。 You'll want to add an <input type=hidden value='num'> or something inside the <div> where num is your number data.您需要在<div>中添加<input type=hidden value='num'>或其他内容,其中num是您的数字数据。 You'll need to make the input field addressable by giving it an ID as well:您还需要通过给它一个 ID 来使输入字段可寻址:

echo("<input type=hidden id=\"$row[id]-num\" value='num'>");

Also, I see a closing div tag but no opening tag.此外,我看到一个结束div标记,但没有开始标记。 You'll want to fix that!你会想要解决这个问题!

Technically you are not supposed to assign custom attributes.从技术上讲,您不应该分配自定义属性。 Jcolebrand's original post is worth an upvote due to the discussion about the data prefix.由于讨论了数据前缀,Jcolebrand 的原始帖子值得一票。 However, even though it is technically not correct, you should be able to get the value with the getAttribute() function.但是,即使它在技术上不正确,您也应该能够使用 getAttribute() function 获取该值。

this.getAttribute("num");

That will work in Firefox, but no guarantees in other browsers.这将在 Firefox 中工作,但在其他浏览器中不能保证。

I've not tried this outside of jQuery, but within that framework you would use我没有在 jQuery 之外尝试过这个,但在那个框架内你会使用

alert(this.attr("num"));

to retrieve non-standard attributes.检索非标准属性。 May work with plain javascript as well, but I've not tried it.也可以与普通的 javascript 一起使用,但我还没有尝试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM