Javascript for loop post form

Javascript for loop post form

本文关键字:form post loop for Javascript      更新时间:2023-09-26

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>

插入.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. 对于循环开始。(x = 0)
  2. 创建表单[0]
  3. 创建所有输入字段并用值填充它们
  4. 提交表单(又名 POST 插入.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/

我猜你在数据库中只记录了myList的第一个元素。这是因为一旦你调用 .submit(),你的 for 循环就会被跳过,页面就会刷新。我建议避免使用表单,只使用使用jQuery发出的简单ajax请求(我看到你已经在使用它)-> http://api.jquery.com/jQuery.post/