Javascript for 循环发布表单

标签 javascript php forms loops submit

for 循环运行来自 facebook api 的数据 (json)。 现在我想将fb数据放入我自己的数据库中(以供其他网站使用)

问题不在于读取数据,而在于提交的某个地方 我好像只能提交1次 我认为 theForm[x] 是问题所在。

代码是:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
  FB.init({
    appId      : ***, // App ID
    status     : true, // check login status
    cookie     : true, // enable cookies to allow the server to access the session
    xfbml      : true  // parse XFBML
  });



  // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
  // for any authentication related change, such as login, logout or session refresh. This means that
  // whenever someone who was previously logged out tries to log in again, the correct case below 
  // will be handled. 
  FB.Event.subscribe('auth.authResponseChange', function(response) {
    // Here we specify what we do with the response anytime this event occurs. 
    if (response.status === 'connected') {
      // The response object is returned with a status field that lets the app know the current
      // login status of the person. In this case, we're handling the situation where they 
      // have logged in to the app.
      testAPI();
    } else if (response.status === 'not_authorized') {
      // In this case, the person is logged into Facebook, but not into the app, so we call
      // FB.login() to prompt them to do so. 
      // In real-life usage, you wouldn't want to immediately prompt someone to login 
      // like this, for two reasons:
      // (1) JavaScript created popup windows are blocked by most browsers unless they 
      // result from direct interaction from people using the app (such as a mouse click)
      // (2) it is a bad experience to be continually prompted to login upon page load
      FB.login(function() {
   // handle the response

        }, {scope: 'friends_relationships,friends_relationship_details,friends_photos,friends_about_me,user_about_me,friends_hometown,friends_location'});

    } else {

      // In this case, the person is not logged into Facebook, so we call the login() 
      // function to prompt them to do so. Note that at this stage there is no indication
      // of whether they are logged into the app. If they aren't then they'll see the Login
      // dialog right after they log in to Facebook. 
      // The same caveats as above apply to the FB.login() call here.
      FB.login(function() {
   // handle the response
        }, {scope: 'friends_relationships,friends_relationship_details,friends_photos,friends_about_me,user_about_me,friends_hometown,friends_location'});

        }
  });
  };


 // Load the SDK asynchronously
  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/all.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));



  // Here we run a very simple test of the Graph API after login is successful. 
  // This testAPI() function is only called in those cases. 
  function testAPI() {
   var $tokenx =   $(FB.getAuthResponse()['accessToken']);
     printTable($tokenx.selector);
    };




    function printTable(token){

    FB.api('/me?fields=name,gender,friends.fields(relationship_status,name,gender,location,picture.width(200).height(200))', function(myList) {



        var theForm = [];
         for (var x = 0 ; x < myList.friends.data.length ; x++){
         console.log(myList.friends.data[x].id + myList.friends.data[x].name);
        // postPage(myList.friends.data[x].id, myList.friends.data[x].name);
         var newInput1, newInput2;
  // Start by creating a <form>
  theForm[x] = document.createElement('form');
  theForm[x].id = x;
  theForm[x].name = x;
  theForm[x].target = "hiddenFrame";
  theForm[x].action = "insert.php";
  theForm[x].method = 'post';
  // Next create the <input>s in the form and give them names and values
  newInput1 = document.createElement('input');
  newInput1.type = 'text';
  newInput1.name = 'id';
  newInput1.value = myList.friends.data[x].id;
  newInput2 = document.createElement('input');
  newInput2.type = 'text';
  newInput2.name = 'naam';
  newInput2.value = myList.friends.data[x].name;
  // Now put everything together...
  theForm[x].appendChild(newInput1);
  theForm[x].appendChild(newInput2);

  theForm[x].submit();
  //document.getElementById(theForm[x]).submit();

         }
         }
            }
            )};



/*          
 function postPage (id2,naam2) {
  var theForm, newInput1, newInput2;
  // Start by creating a <form>
  theForm = document.createElement('form');
  theForm.target = "hiddenFrame";
  theForm.action = "insert.php";
  theForm.method = 'post';
  // Next create the <input>s in the form and give them names and values
  newInput1 = document.createElement('input');
  newInput1.type = 'text';
  newInput1.name = 'id';
  newInput1.value = id2;
  newInput2 = document.createElement('input');
  newInput2.type = 'text';
  newInput2.name = 'naam';
  newInput2.value = naam2;
  // Now put everything together...
  theForm.appendChild(newInput1);
  theForm.appendChild(newInput2);

  theForm.submit();
alert(id2 + " - " + naam2);
};
*/

</script>
<iframe src="insert.php" name="hiddenFrame"></iframe>

<form method="post" action="insert.php" target="hiddenFrame">
naam<input type="text" name="naam"><br>
id<input type="text" name="id">
<input type="submit" name="submit">
</form>
</body>
</html>

insert.php 看起来像(删除了数据库连接“host”、“user”、“pass”、“table”):

<?php
$db=mysql_connect("host","user","pass")or die(mysql_error());
mysql_select_db("table",$db);

$id = $_POST[id];
$naam = $_POST[naam];
$sql = "SELECT COUNT(*) AS count FROM USERS WHERE ID='$id'";
$result = mysql_query($sql);
$result = mysql_fetch_assoc($result);
$count = $result['count'];

echo $count;
echo " - ";
echo $id;


if($count > 0){
   //found

}else{
   $sql="INSERT INTO USERS(ID,NAME)VALUES('$id','$naam')";
    mysql_query($sql,$db);
}

mysql_close($db);
?>

抱歉代码很长,但我认为部分是不可能的 我再次认为 theForm[x] 是问题所在,但我找不到它。

如果有人能指出我正确的方向,我已经非常感谢了。

诗。我知道我的代码很乱:(

最佳答案

theForm[x].submit();

.submit() 就像点击提交按钮。

那么你的脚本中会发生什么:

  1. for 循环开始。 (x = 0)
  2. 创建表单[0]
  3. 创建所有输入字段并用值填充它们
  4. 提交表单(又名 POST 到 insert.php)并“中断”for 循环。

而是使用 jQuery 的 $.post 。它应该看起来像这样:

$.post('insert.php', {id: myList.friends.data[x].id, naam: myList.friends.data[x].name}, function(data){
    // handle response here if required
});

如果您遇到重复帖子/值的问题,可能是因为 $.post 请求是异步的。

查看此页面以获取有关如何执行同步请求的信息... <强> http://api.jquery.com/jQuery.ajax/

关于Javascript for 循环发布表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19552592/

相关文章:

json - 如何在 Easy Admin Bundle 中编辑字段中的 json 数据?

javascript - 在 jQuery 中将相同的元素作为子元素添加到两个不同的父元素是否有效?

javascript - ExtJS 3.动态附加配置

php - 从 php 到 JavaScript 的数组

javascript - 在 Chrome 等浏览器中停止控制台 javascript 命令

html - Bootstrap : align form labels in different rows

javascript - D3 从 Python 函数获取数据

javascript - mongodb——尝试根据查询构建复合索引

php - 如何在页面底部添加页脚 wkhtmltopdf

forms - 内嵌 Bootstrap 表单